1

I am trying to keep my cursor at the end of my editText field so that way users cannot start entering information in the middle. I have tried using a onClickListener and a onTouchListener to set the selection to the length of the editText. Even with trying both of those, the user can still move the cursor to the middle of the text. Is there a way to prevent this?

Caleb Novess
  • 43
  • 1
  • 1
  • 6

1 Answers1

0

You can use myEditText.setSelection(text.length()) to set the cursor at the end of the EditText in conjuction with the onSelectionChanged() method.

Taken from: https://stackoverflow.com/a/12982251/1269953

@Override
public void onSelectionChanged(int start, int end) {

    CharSequence text = getText();
    if (text != null) {
        if (start != text.length() || end != text.length()) {
            setSelection(text.length(), text.length());
            return;
        }
    }

    super.onSelectionChanged(start, end);
}

This will revert the cursor back to the end of the text.

Community
  • 1
  • 1
Pztar
  • 4,274
  • 6
  • 33
  • 39
  • I am a little confused at to how to implement this code into my program – Caleb Novess Apr 24 '17 at 17:33
  • If you look at the link, you'll see that you can override `onSelectionChanged` which is a method available in `EditText`, you will have to create a class that extends EditText and override that method – Pztar Apr 24 '17 at 17:41