Android:edittext restricting text input

Source: Internet
Author: User

Android's edit box control edittext often used in normal programming, sometimes add some restrictions to the edit box, such as limit only enter the number, the maximum number of input text, can not enter some illegal characters, etc. Some of these requirements can be written directly in the layout XML file using the Android control properties, such as android:numeric= "integer" (only allowed to enter numbers);

For some requirements, such as illegal character restrictions (such as not allowed to enter the # number, if the input # gives the error hint), make dynamic judgment more convenient, and easy to expand;

Using the Textwatcher interface in Android makes it easy to listen to the edittext, and there are 3 functions in the textwatcher that need to be overloaded:

    int start,                                  int after);    void aftertextchanged (Editable s); 

From the function name can know its meaning, every time you hit the keyboard edit box text changes, the above three functions will be executed, beforetextchanged can give the content before the change, OnTextChanged and aftertextchanged give the text appended with the new character;

Therefore, the restriction of the character can be determined in the aftertextchanged function, if you check the newly appended word identifier identified illegal characters, then delete it here, then he will not be displayed in the edit box:

New Textwatcher () {    ' # ') { 
//This limit is appended to the string last #
                S.delete (pos,pos+1);                Toast.maketext (myactivity.  "Error letter.", Toast.length_short). Show ();            }     }};

Register for monitoring:

EditText meditor = (EditText) Findviewbyid (r.id.editor_input); Meditor.addtextchangedlistener (Mtextwatcher);

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.