设置editText密码可见性和特殊字符过滤

此方法中的过滤规则可以根据需求自定义,此方法还可以用于其它类型输入检测

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( "`~!@#$%^&*()-_=+,.;':|><?");//特殊字符
        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;
            }
        }});
    }
 
 

猜你喜欢

转载自blog.csdn.net/qi15211/article/details/51303312
今日推荐