EditText最大字符限制超过回调

4

我的想法是在达到最大字符限制时,将错误View设置给EditText。是否有关于此事件的回调函数,或者可能还有其他方法实现这种效果?提前致谢。

4个回答

11

EditText中的maxLength属性实际上是一个InputFilter,你可以自己编写代码并从中提供。你可以查看InputFilter.LengthFilter的实现,如果没有溢出,它基本上会返回null。(参见http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/5.1.1_r1/android/text/InputFilter.java#InputFilter.LengthFilter.filter%28java.lang.CharSequence%2Cint%2Cint%2Candroid.text.Spanned%2Cint%2Cint%29

你可以创建一个扩展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
                editText.setError("Overflow");
            }
            return res;
        }
    }
});

1
很棒的解决方案!优雅且实用。 - Illia K.
2
完美。对于在 Kotlin 中工作的人,当你 override fun filter(): CharSequence? 时,请确保返回类型是可空的 CharSequence,带有一个 ?。 - Bugs Happen

5
你可以使用编辑文本的 setError 方法:setError
editText.addTextChangedListener(new TextWatcher() {         
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable s) {
            if(s.length() > max)
                editText.setError("Error");
        }
    });

1
我正在使用XML中的android:maxLength属性限制最大长度,所以我怀疑这对我不起作用。 - Egor
1
这将不起作用,因为由于maxLength的存在,长度永远不会太长。 - njzk2
你要求“另一种实现此结果的方法”。这是其中之一,将你的maxLength移动到一个常量中并实现它。 - ılǝ

1

我认为最好的解决方案是使用TextChangedListener,并检查EditText测试的长度是否超过了您的限制。


0

谢谢,但是-

editText.setFilters() not editText.setInputFilters()

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接