Get Cursor Position in Android in Edit Text?

AndroidAndroid EdittextAndroid Keypad

Android Problem Overview


I am using a custom EditText View. I have overridden the OnKeyUp event and am able to capture the Enter Key press. Now my requirement is, when the user has entered a text "Hi. How are you?" and then keeps the cursor after the word "are" and press enter, I need to get the cursor location so that i can extract the text after the cursor at the moment the Enter Key was pressed. Please let me know how to do this. Thank you for your time and help.

Android Solutions


Solution 1 - Android

You can get the Cursor position using the getSelectionStart() and getSelectionEnd() methods. If no text is highlighted, both getSelectionStart() and getSelectionEnd() return the position of the cursor. So something like this should do the trick:

myEditText.getSelectionStart();

or

myEditText.getSelectionEnd();

Then if you want to select all the text after the cursor you could use this:

int cursorPosition = myEditText.getSelectionStart();
CharSequence enteredText = myEditText.getText().toString();
CharSequence cursorToEnd = enteredText.subSequence(cursorPosition, enteredText.length());

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionVinodView Question on Stackoverflow
Solution 1 - AndroidtheisenpView Answer on Stackoverflow