1. 程式人生 > >Android中EditText限制僅允許輸入漢字/僅允許漢字和數字

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;
    }