EditText限制输入中文英文最长24个字符

需求:

昵称只可以输入数字,字母,汉字,最长24个字符长度,1个汉字占用2个字符

可以简单的理解:

  1. 最多12个汉字(因为一个汉字就是2个字符了,最长才24个字符)
  2. 24=汉字*2+字母+数字

必然是对EditText进行一番操作了

public class ChineseInputFilter implements InputFilter {

    public ChineseInputFilter(int max_count) {
        this.max_count = max_count;
    }

    private int max_count = 24;//设置最大长度为24个英文字符或者12个中文汉字

    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        if (dest == null || source == null) {
            return null;
        }
        // 判断EditText输入内容+已有内容长度是否超过设定值,超过则做处理 
        if (getTextLengthContainsChinese(dest.toString()) + getTextLengthContainsChinese(source.toString()) > max_count) {

            int destLength = getTextLengthContainsChinese(dest.toString());
            // 已有内容已经有20个字符则返回空字符
            if (destLength >= max_count) {
                return "";
            } else if (destLength == 0) {
                // 已有内容内有0个字符
                return source.toString().substring(0, max_count - destLength);
            } else {
                // 已有内容有若干字符但是不超过20  也大于0个
                int sourceLength = max_count - destLength;
                return source.toString().substring(0, getValidIndex(sourceLength, source.toString()));
            }

        }
        return null;
    }

    /**
     * 获取要截取到位置的索引
     *
     * @param sourceLength
     * @param source
     * @return
     */
    private int getValidIndex(int sourceLength, String source) {
        if (TextUtils.isEmpty(source)) {
            return 0;
        }
        int length = 0;
        for (int i = 0; i < source.length(); i++) {
            if (source.charAt(i) > 255) {
                length += 2;
            } else {
                length++;
            }
            if (length == sourceLength) {
                return i + 1;
            }
            if (length > sourceLength) {
                return i;
            }
        }
        return 0;
    }


    /**
     * 获取文本的长度,中文自增2,其他符号自增1
     *
     * @param text
     * @return
     */
    private int getTextLengthContainsChinese(String text) {
        if (TextUtils.isEmpty(text)) {
            return 0;
        }
        int length = 0;
        for (int i = 0; i < text.length(); i++) {
            if (text.charAt(i) > 255) {
                length += 2;
            } else {
                length++;
            }
        }
        return length;
    }


}

Activity中使用

 InputFilter[] filters = {new ChineseInputFilter(24)};
        edit_name.setFilters(filters);
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值