The edittext control in the editing box of Android is often used in normal programming. Sometimes, some restrictions are added to the editing box. For example, you can only enter numbers and the maximum number of input texts, you cannot enter invalid characters. Some of these requirements can be directly written in the layout XML file using the android control attributes, such as Android: Numeric = "integer" (only numbers are allowed );
For some requirements, such as illegal character restrictions (for example, # is not allowed to be entered. If # is entered, an error prompt is displayed), it is more convenient to make dynamic judgments and easy to expand;
In Android, The textwatcher interface can be used to conveniently listen to edittext. In textwatcher, three functions need to be reloaded:
Public VoidBeforetextchanged (charsequence s,IntStart,IntCount,IntAfter );Public VoidOntextchanged (charsequence s,IntStart,IntBefore,IntCount );Public VoidAftertextchanged (editable S );
The function name can be used to understand the meaning of the function. When the text in the edit box on the keyboard is changed, the above three functions are executed. beforetextchanged can give the content before the change, ontextchanged and aftertextchanged give the text after the new characters are appended;
Therefore, the character restriction judgment can be performed in the aftertextchanged function. If the newly appended character is checked as an illegal character, delete it here, then it will not be displayed in the edit box:
private final textwatcher mtextwatcher = New textwatcher () { Public void beforetextchanged (charsequence s, int Start, int count, int after) {}< SPAN class = "kwrd"> Public void ontextchanged (charsequence s, int Start, int before, int count) {}< SPAN class = "kwrd"> Public void aftertextchanged (editable S) { If (S. length ()> 0) { int Pos = S. length ()-1; char C = S. charat (POS); If (C = '#' ) {
// This limit is added at the end of the string #
S. Delete (Pos, POS + 1); toast. maketext (myactivity.This,"Error letter .", Toast. length_short). Show ();}}}};
Registration listening:
Edittext meditor = (edittext) findviewbyid (R. Id. editor_input); meditor. addtextchangedlistener (mtextwatcher );