需求
输入框内只能输入中英文和数字,而且还要限制最多输入长度为18。
方案
可以使用InputFilter
来过滤输入:
//限制只能输入中文,英文,数字InputFilter typeFilter = new InputFilter() {@Overridepublic CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {Pattern p = pile("[0-9a-zA-Z|\u4e00-\u9fa5]+");Matcher m = p.matcher(source.toString());if (!m.matches()) return "";return null;}};searchEdit.setFilters(new InputFilter[]{typeFilter});
这样就完成了!
之后发现在xml中设置的maxLength
属性失效了,并没有限制最大长度。
分析
为什么会出现这样的情况,我们从TextView
源码中找一下:
我们在TextView构造器中发现
public TextView(Context context, @Nullable AttributeSet attrs, int defStyleAttr, int defStyleRes) {super(context, attrs, defStyleAttr, defStyleRes);...int maxlength = -1;...case com.android.internal.R.styleable.TextView_maxLength:maxlength = a.getInt(attr, -1);break;...if (maxlength >= 0) {setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxlength) });} else {setFilters(NO_FILTERS);}...}
我们可以看到在构造方法中有一个变量maxLength
它对应xml中属性android:maxLength
,如果有值就赋值给变量maxLength
,如果大于等于0,就调用setFilters()
,传入一个InputFilter.LengthFilter
,那么上边我们再次调用setFilters()
,传入我们自己的InputFilter
,就把LengthFilter
覆盖掉了,当然就没有效果了!
所以只能在代码中再添加上长度过滤
//如果要限制输入字数,数组中加上new InputFilter.LengthFilter(maxLength)searchEdit.setFilters(new InputFilter[]{typeFilter, new InputFilter.LengthFilter(18)});