Sometimes you need to have the cursor appear at the specified location in EditText or select some text. Similarly, in order to facilitate user input to enhance the user experience, you may need to make edittext gain or lose focus.
1. Set the cursor to the specified position
- EditText et = (EditText) Findviewbyid(R. ID. Ettest);
- ET. SetSelection(2);
PS: When there is too much content, you can set the cursor position to display the contents of that location on the screen.
2. Hide Cursor
- EditText et = (EditText) Findviewbyid(R. ID. Ettest);
- Set cursor does not display, but cannot set cursor color
- ET. Setcursorvisible(false);
3. Select text when you have focus
- EditText et = (EditText) Findviewbyid(R. ID. Ettest);
- ET. Setselectallonfocus(true);
PS: This method can be used to select the default content when the user taps edittext.
4. Getting and losing focus
- EditText et = (EditText) Findviewbyid(R. ID. Ettest);
- ET. Requestfocus(); //Request to get focus
- ET. Clearfocus(); //Clear Focus
5. Comprehensive application code
- EditText et = (EditText) Findviewbyid(R. ID. Ettest);
- int Index = et. Getselectionstart(); Get cursor location
- String Text="#请在这里输入话题 #";
- Editable Edit = et. Geteditabletext(); Get the EditText text
- If (index < 0 | | | index >= edit. Length() ) {
- Edit. Append(text);
- }Else{
- Edit. Insert(index,text); Insert text where the cursor is located
- }
- ET. SetSelection(index + 1, index + text. ) Length() - 1);
PS: Insert text at the cursor and select # #里面的文本
Organized and adapted from: http://orgcent.com/android-edittext-cursor-position-focus/
[Android Tutorial] EditText set/Hide cursor position, selected text, and get/clear focus