[Android Tutorial] EditText set/Hide cursor position, selected text, and get/clear focus

Source: Internet
Author: User

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

    1. EditText et = (EditText) Findviewbyid(R. ID. Ettest);
    2. 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

    1. EditText et = (EditText) Findviewbyid(R. ID. Ettest);
    2. Set cursor does not display, but cannot set cursor color
    3. ET. Setcursorvisible(false);

3. Select text when you have focus

    1. EditText et = (EditText) Findviewbyid(R. ID. Ettest);
    2. ET. Setselectallonfocus(true);


PS: This method can be used to select the default content when the user taps edittext.
4. Getting and losing focus

    1. EditText et = (EditText) Findviewbyid(R. ID. Ettest);
    2. ET. Requestfocus(); //Request to get focus
    3. ET. Clearfocus(); //Clear Focus

5. Comprehensive application code

  1. EditText et = (EditText) Findviewbyid(R. ID. Ettest);
  2. int Index = et. Getselectionstart(); Get cursor location
  3. String Text="#请在这里输入话题 #";
  4. Editable Edit = et. Geteditabletext(); Get the EditText text
  5. If (index < 0 | | | index >= edit. Length() ) {
  6. Edit. Append(text);
  7. }Else{
  8. Edit. Insert(index,text); Insert text where the cursor is located
  9. }
  10. 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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.