在编辑文本时获取 Android 中的光标位置?

我正在使用自定义 EditText 视图。我已经覆盖了 OnKeyUp 事件,并且能够捕获 Enter 键按下。现在我的要求是,当用户输入一个文本“ Hi。你好吗?”然后保持光标后面的单词“是”和按回车,我需要得到光标的位置,这样我就可以提取的文本后,光标的时刻回车键被按下。请告诉我该怎么做。谢谢你的时间和帮助。

62151 次浏览

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