Recently, the password modification function is used in a project. However, we do not want users to enter Chinese or special characters for Password Input. Therefore, we need to filter the input boxes of users, the following is a small code snippet for filtering EditText:
1. First, add a TextWatcher to Edittext. Of course, this TextWatcher must be written by ourselves. The core functions are also in this class.
[Java]
MOldPwdET. addTextChangedListener (new SearchWather (mOldPwdET ));
2. The following is the custom TextWatcher.
[Java]
Class SearchWather implements TextWatcher {
// Monitor the changed text box
Private EditText editText;
/**
* Constructor
*/
Public SearchWather (EditText editText ){
This. editText = editText;
}
@ Override
Public void onTextChanged (CharSequence ss, int start, int before, int count ){
String editable = editText. getText (). toString ();
String str = stringFilter (editable. toString ());
If (! Editable. equals (str )){
EditText. setText (str );
// Set the position of the new cursor www.2cto.com
EditText. setSelection (str. length ());
}
}
@ Override
Public void afterTextChanged (Editable s ){
}
@ Override
Public void beforeTextChanged (CharSequence s, int start, int count, int after ){
}
}
Public static String stringFilter (String str) throws PatternSyntaxException {
// Only letters and numbers are allowed
String regEx = "[^ a-zA-Z0-9]";
Pattern p = Pattern. compile (regEx );
Matcher m = p. matcher (str );
Return m. replaceAll (""). trim ();
}
I hope you can share with us any better solutions.
Author jamin0107