Home>

Android edit box control edittext is often used in ordinary programming,Sometimes add some restrictions to the edit box,If you can only enter numbers,Maximum number of characters entered,Can't enter some illegal characters, etc.Some of these requirements can be written directly in the layout xml file using android control attributes, such as android:numeric="integer" (only numbers can be entered);

For some needs,Such as illegal character restrictions (such as not allowed to enter the #sign, if you enter #to give an error prompt), it is more convenient to make a dynamic judgment,And easy to expand;

Using textwatcher interface in android can easily monitor edittext;There are 3 functions in textwatcher that need to be overloaded:

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 know the meaning from the function name,Whenever the text on the keyboard edit box changes,All three functions above will be executed,beforetextchanged can give the content before the change,ontextchanged and aftertextchanged give the text after appending new characters;

Therefore, the character limit judgment can be performed in the aftertextchanged function.If it is detected that the newly appended character is a recognized illegal character,Then delete it here, so he 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) {
 }
 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 limited to append at the end of the string #
    s.delete (pos, pos + 1);
    toast.maketext (myactivity.this, "error letter.", toast.length_short) .show ();
   }
  }
 }
};

Register to listen:

edittext meditor=(edittext) findviewbyid (r.id.editor_input);
meditor.addtextchangedlistener (mtextwatcher);
  • Previous Detailed explanation of Android timed task process
  • Next Detailed classes and structures in the Swift language