An EditText method of restricting text input in Android programming

  • 2020-10-23 21:12:32
  • OfStack

This article gives an example of how EditText restricts text input in Android programming. To share for your reference, the details are as follows:

EditText Android the edit box controls would be often used in ordinary programming, sometimes adding some restrictions to the edit box, such as limit can only input Numbers, the largest number of text input cannot enter 1 some illegal characters, etc., some of these requirements can use android control properties to write directly in xml file layout, such as android: numeric = "integer" (only allow input number);

For some requirements, such as illegal character limits (for example, no # is allowed, if # is entered, an error is given), it is more convenient to make dynamic judgment.

Using the TextWatcher interface in Android makes it easy to listen to EditText. There are three functions in TextWatcher that need to be overridden:


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

The above three functions are executed every time the text in the keyboard edit box is changed. beforeTextChanged gives the content before the change. onTextChanged and afterTextChanged give the text after the new character is appended.

Therefore, the judgment of character restriction can be carried out in the afterTextChanged function. If it is found that the newly appended character is considered illegal, then delete will be dropped here, and 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) {
 } 
 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 == '#') {
   // This limits appending to the end of the string #
    s.delete(pos,pos+1);
    Toast.makeText(MyActivity.this, "Error letter.",Toast.LENGTH_SHORT).show();
   }
  }
 }
};

Register for listening:


EditText mEditor = (EditText)findViewById(R.id.editor_input);
mEditor.addTextChangedListener(mTextWatcher);

I hope this article has been helpful in Android programming.


Related articles: