原因
maxLength作为一个属性,也是用inputFilter实现的。如果自定义了inputFilter,就会覆盖掉原本maxLength的这个inputFilter,所以无效。
探究
EditText控件里没有maxLength这个属性
EditText继承TextView
TextView里有maxLength这个属性
设置maxLength的代码
if (maxlength >= 0) {
setFilters(new InputFilter[] { new InputFilter.LengthFilter(maxlength) });
} else {
setFilters(NO_FILTERS);
}
看看LengthFilter的代码
public static class LengthFilter implements InputFilter {
private final int mMax;`
public LengthFilter(int max) {
mMax = max;
}
public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
int dstart, int dend) {
int keep = mMax - (dest.length() - (dend - dstart));
if (keep <= 0) {
return "";
} else if (keep >= end - start) {
return null; // keep original
} else {
keep += start;
if (Character.isHighSurrogate(source.charAt(keep - 1))) {
--keep;
if (keep == start) {
return "";
}
}
return source.subSequence(start, keep);
}
}
/**
* @return the maximum length enforced by this input filter
*/
public int getMax() {
return mMax;
}
}
int keep = mMax - (dest.length() - (dend - dstart));
这一行是计算还留有多少字符可以输入的
逻辑不复杂
**不过dend-dstart 我不明白,这两个值我测试在大部分情况下是一样的,删除字符情况下,dend-dstart = 1; **