1200字范文,内容丰富有趣,写作的好帮手!
1200字范文 > Android限制输入框输入中英文和数字 并限制个数

Android限制输入框输入中英文和数字 并限制个数

时间:2019-11-08 09:08:35

相关推荐

Android限制输入框输入中英文和数字 并限制个数

需求

输入框内只能输入中英文和数字,而且还要限制最多输入长度为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)});

本内容不代表本网观点和政治立场,如有侵犯你的权益请联系我们处理。
网友评论
网友评论仅供其表达个人看法,并不表明网站立场。