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

Vin*_*nod 65 android android-keypad android-edittext

我正在使用自定义的EditText视图.我已经覆盖了OnKeyUp事件,并且能够捕获Enter键按下.现在我的要求是,当用户输入文字"你好.你好吗?" 然后将光标保持在单词"are"之后并按回车键,我需要获取光标位置,以便我可以在按下Enter键时提取光标后的文本.请让我知道如何做到这一点.感谢您的时间和帮助.

the*_*enp 147

您可以使用getSelectionStart()和getSelectionEnd()方法获取Cursor位置.如果没有突出显示文本,则getSelectionStart()和getSelectionEnd()都将返回游标的位置.所以像这样的东西应该做的伎俩:

myEditText.getSelectionStart();
Run Code Online (Sandbox Code Playgroud)

要么

myEditText.getSelectionEnd();
Run Code Online (Sandbox Code Playgroud)

然后,如果要选择光标后的所有文本,可以使用:

int cursorPosition = myEditText.getSelectionStart();
CharSequence enteredText = myEditText.getText().toString();
CharSequence cursorToEnd = enteredText.subSequence(cursorPosition, enteredText.length());
Run Code Online (Sandbox Code Playgroud)

  • 了解 getSelectionEnd 和 getSelection start 可能对某些人有所帮助,它们是 Selection 类中的静态方法,而不是 EditText 本身的静态方法。以下是文档:https://developer.android.com/reference/android/text/Selection (2认同)