android Edittext限制字符长度.文字字母

直接抄就行

edittext.setFilters(new InputFilter[]{new LengthFilterUtil(18)});
public class LengthFilterUtil implements InputFilter {
    private final int maxLength;

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

    public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                               int dstart, int dend) {
        //限定字符数量
        int dindex = 0;
        int count = 0;
        //计算文本框中已经存在的字符长度
        while (count <= maxLength && dindex < dest.length()) {
            char c = dest.charAt(dindex++);
            //这里是根据ACSII值进行判定的中英文,其中中文及中文符号的ACSII值都是大于128的
            if ((int) c <= 128) {
                count += 1;
            } else {
                count += 2;
            }
        }

        if (count > maxLength) {
            return dest.subSequence(0, dindex - 1);
        }
        //计算输入的字符长度
        int sindex = 0;
        while (count <= maxLength && sindex < source.length()) {
            char c = source.charAt(sindex++);
            if ((int) c <= 128) {
                count += 1;
            } else {
                count += 2;
            }
        }
        if (count > maxLength) {
            sindex--;
        }
        return source.subSequence(0, sindex);
    }
}

你可能感兴趣的:(android Edittext限制字符长度.文字字母)