設定editText密碼可見性和特殊字元過濾
阿新 • • 發佈:2018-11-07
此方法中的過濾規則可以根據需求自定義,此方法還可以用於其它型別輸入檢測
private static boolean checkLegalCharacters(String name, boolean isPasswd) {
Pattern p1 = Pattern.compile("[0-9]*");//數字Pattern p2 = Pattern.compile("[a-zA-Z]");//字母
Pattern p3 = Pattern.compile("[\u4e00-\u9fa5]");//中文
String specialCharacters = "`
// Pattern p4 = Pattern.compile( "`[email protected]#$%^&*()-_=+,.;':|><?");//特殊字元
String n = "";
for (int i = 0; i < name.length(); i++) {
n = name.substring(i, i + 1);
Matcher m1 = p1.matcher(n);
Matcher m2 = p2.matcher(n);
if (isPasswd) {
// Matcher m4 = p4.matcher(n);
// LogHelper.i("test","!m4.matches()=="+m4.matches()+"==="+name+"==="+n);
if (!m1.matches() && !m2.matches() && !specialCharacters.contains(n)) {
// if (!m1.matches() && !m2.matches() && !m4.matches()) {
return false;
}
} else {
Matcher m3 = p3.matcher(n);
if (!m1.matches() && !m2.matches() && !m3.matches()) {
return false;
}
}
}
return true;
}
**************************************
/** * @Name:setPasswordVisible * @Description:TODO * @param:@param editText * @param:@param passwdHin true隱藏密碼 * @return:void */ public static void setPasswordVisible(EditText editText, boolean passwdHin) { if(!passwdHin) { // 顯示密碼 // editText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); editText.setTransformationMethod(PasswordTransformationMethod.getInstance()); } else { // 隱藏密碼 // editText.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_PASSWORD); editText.setTransformationMethod(HideReturnsTransformationMethod.getInstance()); } // editText.postInvalidate(); editText.setSelection(editText.getText().length()); editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(18), new InputFilter() { @Override public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) { for (int i = start; i < end; i++) { String s = Character.toString(source.charAt(i)); if (!checkLegalCharacters(s, true)) { return ""; } } return null; } }}); }