Android edittext限制字符数

et.setFilters(new InputFilter[]{new LengthFilterUtil(18)});


public class LengthFilterUtil implements InputFilter {
    private final int maxLength;

    public LengthFilterUtil(int max) {
        maxLength = max;
    }

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        // 输入内容是否超过设定值,最多输入五个汉字10个字符
        if (getTextLength(dest.toString()) + getTextLength(source.toString()) > maxLength) {
            // 输入框内已经有10个字符则返回空字符
            if (getTextLength(dest.toString()) >= 10) {
                return "";
                // 如果输入框内没有字符,且输入的超过了10个字符,则截取前五个汉字
            } else if (getTextLength(dest.toString()) == 0) {
                return source.toString().substring(0, 5);
            } else {
                // 输入框已有的字符数为双数还是单数
                if (getTextLength(dest.toString()) % 2 == 0) {
                    return source.toString().substring(0, 5 - (getTextLength(dest.toString()) / 2));
                } else {
                    return source.toString().substring(0, 5 - (getTextLength(dest.toString()) / 2 + 1));
                }
            }
        }
        return null;
    }

    public static int getTextLength(String text) {
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) > 255) {
                length += 2;
            } else {
                length++;
            }
        }
        return length;
    }
}

你可能感兴趣的:(Android edittext限制字符数)