getSelectionStart() doesn't work in android

2019-08-31 04:27发布

问题:

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());