• Android EditText 文本长度限制(按照一个汉字占俩长度 类似字节)


    Android EditText 文本长度限制有很简单的一种限制方式:在xml布局文件中对EditText添加 Android:maxLength="N" 

    但是这种简单的方式可能有时候不能满足某些比较较真的需求,这个时候就需要用别的的方式去限制长度了。

    也就是通过InputFilter来实现:

    private class NameLengthFilter implements InputFilter {
            int MAX_EN;
            String regEx = "[\u4e00-\u9fa5]";
    
            public NameLengthFilter(int mAX_EN) {
                super();
                MAX_EN = mAX_EN;
            }
    
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {
                int destCount = dest.toString().length()
                        + getChineseCount(dest.toString());
                int sourceCount = source.toString().length()
                        + getChineseCount(source.toString());
                if (destCount + sourceCount > MAX_EN) {
                    int surplusCount = MAX_EN - destCount;
                    String result = "";
                    int index = 0;
                    while (surplusCount > 0) {
                        char c = source.charAt(index);
                        if (isChinest(c + "")) {
                            if (sourceCount >= 2) {
                                result += c;
                            }
                            surplusCount = surplusCount - 2;
                        } else {
                            result += c;
                            surplusCount = surplusCount - 1;
                        }
                        index++;
                    }
                    return result;
                } else {
                    return source;
                }
            }
    
            private int getChineseCount(String str) {
                int count = 0;
                Pattern p = Pattern.compile(regEx);
                Matcher m = p.matcher(str);
                while (m.find()) {
                    for (int i = 0; i <= m.groupCount(); i++) {
                        count = count + 1;
                    }
                }
                return count;
            }
    
            private boolean isChinest(String source) {
                return Pattern.matches(regEx, source);
            }
        }

    以上是自定义的Filter,给需要的EditText设置就OK了:

    ed_nane.setFilters(filters);

    可能某些代码比较low,但是可以用。

  • 相关阅读:
    体验用yarp连接websocket
    从 ASP.NET Core 5.0 迁移到.NET 6
    对接网易云信音视频2.0呼叫组件集成到vue中,实现web端呼叫app,视频语音通话。
    .NET6 WebAPI 自定义过滤器
    .NET6 WebApi 获取访问者IP地址
    .NET6 部署到 IIS
    .NET6 WebApi JSON传到前台默认变成小驼峰
    开发环境 测试环境 生产环境
    .NET6 WebApi 使用 log4net
    .NET6 WebApi 解决跨域问题
  • 原文地址:https://www.cnblogs.com/mauiie/p/5557199.html
Copyright © 2020-2023  润新知