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

  • 相关阅读:
    hibernate 批量增加 修改 删除
    Java WebService入门实例
    linux中Jetty的安装和配置
    Jetty与tomcat的比较
    在云上搭建大规模实时数据流处理系统
    大型开源日志系统比较
    JMX整理
    Gradle笔记——Gradle的简介与安装
    Groovy入门教程
    Apache Maven 入门篇 ( 上 )
  • 原文地址:https://www.cnblogs.com/wzzkaifa/p/7262738.html
Copyright © 2020-2023  润新知