1. 程式人生 > >利用InputFilter限制輸入的型別以及字數

利用InputFilter限制輸入的型別以及字數

private InputFilter mInputFilter;
private InputFilter mInputFilterLengh;
mInputFilter = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String stringSourse = source.toString();
                StringBuilder stringBuilder = new
StringBuilder(); for (int i = 0; i < stringSourse.length(); i++) { char ch = stringSourse.charAt(i); //只可以輸入數字、字母、漢字 String regEx = "[a-zA-Z0-9\u4E00-\u9FA5]"; Pattern p = Pattern.compile(regEx); Matcher m = p.matcher(ch + ""
); if (m.matches()) { stringBuilder.append(ch); } } return stringBuilder; } }; mInputFilterLengh = new InputFilter.LengthFilter(30); mEditTextBranch.setFilters(new InputFilter[]{mInputFilter,mInputFilterLengh});