试图在 EditText 中设置 maxLength,但字符仍然可以超过 max

Trying to set maxLength in EditText, but characters can still go beyond max

我正在尝试将 EditText 的最大长度设置为 2,这样用户就不能输入超过 2 个字符的缩写。但是当 运行 代码时,我仍然可以输入任意数量的字符。我实现 maxLength 的方式有问题吗?

<EditText
                    android:id="@+id/register_edit_stcn"
                    android:maxLength="2"
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:layout_gravity="center"
                    android:layout_weight="1"
                    android:background="#00000000"
                    android:capitalize="sentences"
                    android:gravity="left"
                    android:hint="ST OR CN"
                    android:inputType="text"
                    android:letterSpacing="0.095"
                    android:textAllCaps="true"
                    android:textColor="#FFF"
                    android:textSize="16dp" />

当您手动添加 InputFilter 对象时,xml 属性 被覆盖,因此它会将 maxLength 重置为其默认值。

is there a way to limit character limit while still having InputFilter?

你可以试试这个:

创建自定义输入过滤器class:

package com.test;

import android.text.InputFilter;
import android.text.Spanned;

public class InputFilterMinMax implements InputFilter {

    private int min, max;

    public InputFilterMinMax(int min, int max) {
        this.min = min;
        this.max = max;
    }

    public InputFilterMinMax(String min, String max) {
        this.min = Integer.parseInt(min);
        this.max = Integer.parseInt(max);
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {   
        try {
            int input = Integer.parseInt(dest.toString() + source.toString());
            if (isInRange(min, max, input))
                return null;
        } catch (NumberFormatException nfe) { }     
        return "";
    }

    private boolean isInRange(int a, int b, int c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

register_edit_stcn.setFilters(new InputFilter[]{new InputFilterMinMax("0", "2"), new InputFilter.LengthFilter(2)});

感谢@Pratik Sharma

this solution

我已经测试了这段代码并且它有效。您不能输入超过 3 个字符,因为 maxLength=3

    EditText message = (EditText) findViewById(R.id.register_edit_stcn);
    int maxLength = 3;
    message.setFilters(new InputFilter[] {new InputFilter.LengthFilter(maxLength)});