在使用InputFilter.LengthFilter为editText设置最大字符限制后,有没有办法使editText在达到最大字符数后仍能触发onTextChanged事件?如果没有,有没有简单的方法为editText设置最大字符数并在onTextChanged事件中仍然能够触发?
在使用InputFilter.LengthFilter为editText设置最大字符限制后,有没有办法使editText在达到最大字符数后仍能触发onTextChanged事件?如果没有,有没有简单的方法为editText设置最大字符数并在onTextChanged事件中仍然能够触发?
在XML中为EditText添加以下属性:
android:maxLength="20"
我曾经遇到同样的问题,在 Stack Overflow 上进行了一些研究,找到了这个解决方案。感谢 @njzk2 提供的绝妙解决方案。在此发布,以便其他人可以得到答案。
EditText
中的 maxLength
属性实际上是一个 InputFilter
,您可以自己编写并从代码中提供。
您可以查看 InputFilter.LengthFilter 的实现,如果没有溢出,它基本上会返回 null
。(请参见 link)
稍加修改即可:创建一个扩展 InputFilter.LengthFilter
的类,在其中调用 super
并将其与 null
进行比较,以决定是否需要显示警报。
editText.setInputFilters(new InputFilter[] {
new InputFilter.LengthFilter(max) {
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
CharSequence res = super.filter(source, start, end, dest, dstart, dend);
if (res != null) { // Overflow
Toast.makeText(this,"OVERFLOW!",Toast.LENGTH_SHORT).show();
}
return res;
}
}
});