getSelectionStart() doesn't work in android

匿名 (未验证) 提交于 2019-12-03 01:26:01

问题:

I want to get EditText selection start when user click in EditText (touch).
I do with this code :

int startIndex = txtMean.getSelectionStart(); 

this always return 0;

and EditText xml code:

<EditText                 android:id="@+id/txtMean"                 android:layout_width="match_parent"                 android:layout_height="wrap_content"                 android:background="@null"                 android:clickable="true"                 android:focusable="true"                 android:focusableInTouchMode="true"                 android:hint=""                 android:inputType="textMultiLine"                 android:scrollbars="none" /> 

my code work in android 2.* but don't work in 4.*

回答1:

  txtMean.getSelectionStart(); 

getSelectionStart doesn't relate to the user's last touch or click per se. It relates to the text selection on the screen. By default, when the user does a long click text-handles will come up, and allow the user to expand a highlighted text selection. It's the highlighted text that refers to the selection, which is not necessarily where the user last touched.

When the user makes a text selection it becomes highlighted because the EditText will apply a SelectionSpan to the character sequence, and getSelectionStart will return the start value of this span.

Update, Solution Help:

@Override public boolean onTouchEvent(MotionEvent event) {    // this = EditText;   // will give you the position of the nearest chracter.       int offset = this.getOffsetForPosition(event.getX(), event.getY());  


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!