android EditText 限定中文个数与英文个数的解决方式

EditText 限定中文8个英文16个的解决方法。

在EditText上控件提供的属性中有限定最大最小长度的方法。

可是,对于输入时,限定中文8个英文16个时,怎么办?相当于一个中文的长度是两个英文的长度。

原理就不说了。自己看一下android的源代码。

以上直接上代码。


private final int maxLen = 16;
private InputFilter filter = new InputFilter() {

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int dindex = 0;
        int count = 0;

        while (count <= maxLen && dindex < dest.length()) {
            char c = dest.charAt(dindex++);
            if (c < 128) {
                count = count + 1;
            } else {
                count = count + 2;
            }
        }

        if (count > maxLen) {
            return dest.subSequence(0, dindex - 1);
        }

        int sindex = 0;
        while (count <= maxLen && sindex < source.length()) {
            char c = source.charAt(sindex++);
            if (c < 128) {
                count = count + 1;
            } else {
                count = count + 2;
            }
        }

        if (count > maxLen) {
            sindex--;
        }

        return source.subSequence(0, sindex);
    }


};

使用例如以下:

editText.setFilters(new InputFilter[]{filter});

原文地址:https://www.cnblogs.com/wzzkaifa/p/7262738.html