Android中EditText限制仅允许输入汉字/仅允许汉字和数字

最近项目各种需求,各种更改,之前的需求是editText只要不是数字就ok了.
现在需求改为只允许输入汉字,采用正则表达式完成.

@BindView(R2.id.et_other_college)
EditText etOtherCollege;

自定义一个方法:

public static String stringFilter1(String str) throws PatternSyntaxException {
    //只允许汉字
    String regEx = "[^\u4E00-\u9FA5]";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(str);
    return m.replaceAll("").trim();
}

在EditText中监听

 //学校 限制仅汉字
 etOtherCollege.addTextChangedListener(new TextWatcher() {
       String str;
       @Override
       public void beforeTextChanged(CharSequence s, int start, int count, int after) {

       }

       @Override
       public void onTextChanged(CharSequence s, int start, int before, int count) {
           String strs=etOtherCollege.getText().toString();
           str = stringFilter1(strs.toString());
           if (!strs.equals(str)) {
               etOtherCollege.setText(str);
               etOtherCollege.setSelection(str.length());
            }
       }

       @Override
       public void afterTextChanged(Editable editable) {

       }
});

仅限数字和汉字的方法:(同理只需改变正则表达式即可)

public static String stringFilter2(String str) throws PatternSyntaxException {
    //只允许数字和汉字
    String regEx = "[^0-9\u4E00-\u9FA5]";
    Pattern p = Pattern.compile(regEx);
    Matcher m = p.matcher(str);
    return m.replaceAll("").trim();
}

例外,项目之前的需求是只要不是数字,也就是可以是符号,除了正则还有一种方法

InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
                             Spanned dest, int dstart, int dend) {
   for (int i = start; i < end; i++) {
     if (!isChinese(source.charAt(i))) {
        return "";
     }
   }
   return null;
  }
};
etOtherCollege.setFilters(new InputFilter[]{filter, new InputFilter.LengthFilter(18)});
private boolean isChinese(char c) {
        Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
        if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
                || ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
                || ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
                || ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
                || ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
            return true;
        }
        return false;
    }

你可能感兴趣的:(Android控件)