Android: EditText text input restrictions

Original link: http://www.cnblogs.com/butterfly-clover/p/5453471.html

  Android EditText edit box control will be frequently used in the usual programming, sometimes the edit box will add some restrictions, such as limiting the numerical only, the maximum number of text input, you can not enter illegal characters, etc., some of these needs android control properties can be used to write directly in the layout xml file, such as android: numeric = "integer" (only allowed to enter the number);

For some requirements, such as illegal characters limit (e.g. not allowed to enter the number #, # if given an input error), the dynamic determination is made more convenient, and easy to expand;

Use TextWatcher interfaces can easily listen in on EditText in Android; TextWatcher There are three functions need to override:

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

From the function name can know its meaning, each time typing on the keyboard to change the text edit box, the above three functions will be executed, beforeTextChanged content can be given before the change, onTextChanged and afterTextChanged new character is given after the additional text;

So judge the character limit can be carried out in afterTextChanged function, to check if the newly added characters identified as illegal characters, then delete it out here, then he would 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 (the Editable S) {
         IF (s.length ()> 0 ) {
             int POS = s.length () -. 1 ;
             char C = s.charAt (POS);
             IF (C == '#' ) {
 // limit here in the last string added s.delete # (POS, POS + 1); 
                Toast.makeText (. myactivity the this , "Error Letter." , Toast.LENGTH_SHORT) .Show ();
            }
        }
    }
};

 Registration listeners:

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

 

Reproduced in: https: //www.cnblogs.com/butterfly-clover/p/5453471.html

Guess you like

Origin blog.csdn.net/weixin_30707875/article/details/94860977