• 限制EditText最多输入多少汉字


    mInputEditText.setFilters(new InputFilter[]{new InputLengthFilter(MAX_INPUT_SIZE)});



    public class InputLengthFilter implements InputFilter {

    private final int mMax;

    public InputLengthFilter(int max) {
    //mMax = max*2;
    mMax = max;
    }

    /**
    *
    * @param source 新输入的字符串
    * @param start 新输入的字符串起始下标,一般为0
    * @param end 新输入的字符串终点下标,一般为source长度-1
    * @param dest 输入之前文本框内容
    * @param dstart 原内容起始坐标,一般为0
    * @param dend 原内容终点坐标,一般为dest长度-1
    * @return
    */
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
    int destSize = dest.length();
    int spill = 0;
    //无须区别对待汉字, 需求为1中文=1标点=1数字=1符号,表情[微笑]相当于4个中文长度
    // for(int i=0;i<destSize;i++){
    // char c = dest.charAt(i);
    // if((char)(byte)c!=c){//中文
    // spill ++;
    // }
    // }
    int keep = mMax - (destSize + spill - (dend - dstart));

    if (keep <= 0) {
    return "";
    } else if (keep >= end - start) {
    return null; // keep original
    } else {
    keep += start;
    if (Character.isHighSurrogate(source.charAt(keep - 1))) {
    --keep;
    if (keep == start) {
    return "";
    }
    }
    int sourceSpill = 0;
    int size = source.length();
    for(int i=0;i<size;i++){
    //同上
    // char c = source.charAt(i);
    // if((char)(byte)c!=c){//中文
    // sourceSpill ++;
    // }
    if(keep <= sourceSpill+i){
    return source.subSequence(start, i);
    }
    }
    return source.subSequence(start, keep);
    }
    }
    }
  • 相关阅读:
    The Elements of C# Style Design
    The Elements of C# Style Programming
    The Elements of C# Style General Principles
    浅谈CLR
    堆排序
    WPF系列:GridView列绑定控件(一)
    分发服务器迁移(distribute service migration‏)
    通过编码规范来学习一门编程语言
    如何维护数据库中的静态表
    关于短地址服务的一些看法
  • 原文地址:https://www.cnblogs.com/wutianlong/p/6122835.html
Copyright © 2020-2023  润新知