This article illustrates the EditText method of restricting text input in Android programming. Share to everyone for your reference, specific as follows:
The Android edit box control EditText is often used in normal programming, sometimes adding some restrictions to the edit box, such as limiting the number of characters you can enter, the number of text you can enter, Some of these requirements can be written directly in the layout XML file using the Android control properties, such as android:numeric= "integer" (only allow numbers to be entered);
For some requirements, such as illegal character restrictions (such as not allowed to enter the #, if you enter the # to give error prompts), make dynamic judgments more convenient, and easy to expand;
Using the Textwatcher interface in Android makes it easy to listen to EditText; there are 3 functions in textwatcher that require overloading:
public void beforetextchanged (charsequence s, int start, int count, int after);
public void ontextchanged (charsequence s, int start, int before, int count);
public void aftertextchanged (Editable s);
You can tell the meaning from the function name, and whenever the text of the keyboard editing box is changed, the three functions above will be executed, beforetextchanged can give the content before the change, OnTextChanged and aftertextchanged give the text after the new character is appended;
Therefore, the restriction on the character can be judged in the aftertextchanged function, if you check the new appended word identifier illegal characters, then delete it here, then he will not appear in the edit box:
Private final Textwatcher Mtextwatcher = new Textwatcher () {public
void beforetextchanged (charsequence s, int start, int count, int after] {
} public
void OnTextChanged (charsequence s, int start, int before, int count) {
}
public void aftertextchanged (Editable s) {
if (s.length () > 0) {
int pos = s.length ()-1;
char c = S.charat (POS);
if (c = = ' # ') {
//Here is restricted at the end of the string appended #
S.delete (pos,pos+1);
Toast.maketext (myactivity.this, "Error letter.", Toast.length_short). Show ();
Registration Monitor:
EditText meditor = (edittext) Findviewbyid (r.id.editor_input);
Meditor.addtextchangedlistener (Mtextwatcher);
I hope this article will help you with the Android program.