zoukankan      html  css  js  c++  java
  • 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});

  • 相关阅读:
    IntelliJ IDEA基本设置
    git安装
    Git的作用与安装
    git是什么
    SpringMVC控制器类方法的返回值
    SpringMVC中Model机制
    什么是Nosql
    如何使用Jedis操作redis
    redis中数据类型操作命令
    redis的全局命令
  • 原文地址:https://www.cnblogs.com/wzzkaifa/p/7262738.html
Copyright © 2011-2022 走看看