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);