問題描述
我正在使用自定義的 EditText 視圖.我已經覆蓋了 OnKeyUp 事件并且能夠捕獲 Enter 按鍵.現在我的要求是,當用戶輸入文本嗨.你好嗎?"然后將光標保持在單詞are"之后并按Enter,我需要獲取光標位置,以便在按下Enter鍵時提取光標后的文本.請讓我知道如何做到這一點.感謝您的時間和幫助.
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.
推薦答案
您可以使用 getSelectionStart() 和 getSelectionEnd() 方法獲取光標位置.如果沒有突出顯示文本,getSelectionStart() 和 getSelectionEnd() 都會返回光標的位置.所以這樣的事情應該可以解決問題:
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();
或
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());
這篇關于在編輯文本中獲取 Android 中的光標位置?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!