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});

  • 相关阅读:
    课上作业
    大道至简第四章读后感
    课上作业
    读大道至简第三章感想
    关于外部引用JS,中文乱码的问题
    HTML5 之Canvas绘制太阳系
    HTML5 之Canvas 绘制时钟 Demo
    JQuery仿淘宝商家后台管理 之 管理添加分类
    分页存储过程的几种写法
    Javascript-do_while....
  • 原文地址:https://www.cnblogs.com/wzzkaifa/p/7262738.html
Copyright © 2011-2022 走看看