首先在Activity中编写下列静态方法:
public static String stringFilter(String str)throws PatternSyntaxException {
String regEx = "[/\\:*?<>|\'\"\n\t]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("");
}
再将onCreat中实现EditText的检查代码:
mEditText = (EditText)findViewById(R.id.reg_repassword);
mEditText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
String editable = mEditText.getText().toString();
String str = stringFilter(editable);
if (!editable.equals(str)) {
Toast.makeText(getApplicationContext(), "特殊字符已被删除,请继续!", Toast.LENGTH_SHORT).show();
mEditText.setText(str);
CharSequence text = mEditText.getText();
if (text instanceof Spannable) {
Spannable spanText = (Spannable) text;
Selection.setSelection(spanText, text.length());
}
}
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void afterTextChanged(Editable s) {
}
});