hxb
2022-11-22 b3513b1713bb979d0a69c5a8c4ddcd038f184e6e
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
package com.mm.android.deviceaddmodule.mobilecommon.utils;
 
import android.text.InputFilter;
import android.text.Spanned;
 
 
public class NameLengthFilter implements InputFilter {
 
    private final int mMax;
 
    public NameLengthFilter(int max) {
        mMax = max;
    }
 
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        int destCount = getWordCountRegex(dest.toString());
        int sourceCount = getWordCountRegex(source.toString());
        if(destCount + sourceCount > mMax){
            int surplusCount = mMax - destCount;
            String result = "";
            int resultCount = 0;
            int index = 0;
            while (surplusCount > resultCount){
                result += source.charAt(index);
                resultCount = getWordCountRegex(result);
                index++;
            }
 
            if(surplusCount == resultCount){
                return source.subSequence(start, index);
            }else{
                return source.subSequence(start, index - 1);
            }
 
        }else{
            return source;
        }
 
    }
 
    private int getWordCountRegex(String str){
        if(str == null){
            return 0;
        }
 
        str = str.replaceAll("[^\\x00-\\xff]" , "**");
        return str.length();
    }
}