Android EditText 文本长度限制(按照一个汉字占俩长度 类似字节)

Android EditText 文本长度限制有很简单的一种限制方式:在xml布局文件中对EditText添加 Android:maxLength="N" 

但是这种简单的方式可能有时候不能满足某些比较较真的需求,这个时候就需要用别的的方式去限制长度了。

也就是通过InputFilter来实现:

private class NameLengthFilter implements InputFilter {
        int MAX_EN;
        String regEx = "[\u4e00-\u9fa5]";

        public NameLengthFilter(int mAX_EN) {
            super();
            MAX_EN = mAX_EN;
        }

        @Override
        public CharSequence filter(CharSequence source, int start, int end,
                                   Spanned dest, int dstart, int dend) {
            int destCount = dest.toString().length()
                    + getChineseCount(dest.toString());
            int sourceCount = source.toString().length()
                    + getChineseCount(source.toString());
            if (destCount + sourceCount > MAX_EN) {
                int surplusCount = MAX_EN - destCount;
                String result = "";
                int index = 0;
                while (surplusCount > 0) {
                    char c = source.charAt(index);
                    if (isChinest(c + "")) {
                        if (sourceCount >= 2) {
                            result += c;
                        }
                        surplusCount = surplusCount - 2;
                    } else {
                        result += c;
                        surplusCount = surplusCount - 1;
                    }
                    index++;
                }
                return result;
            } else {
                return source;
            }
        }

        private int getChineseCount(String str) {
            int count = 0;
            Pattern p = Pattern.compile(regEx);
            Matcher m = p.matcher(str);
            while (m.find()) {
                for (int i = 0; i <= m.groupCount(); i++) {
                    count = count + 1;
                }
            }
            return count;
        }

        private boolean isChinest(String source) {
            return Pattern.matches(regEx, source);
        }
    }

以上是自定义的Filter,给需要的EditText设置就OK了:

ed_nane.setFilters(filters);

可能某些代码比较low,但是可以用。

原文地址:https://www.cnblogs.com/mauiie/p/5557199.html