有时产品经理提的需求,要区分中文英文字符长度,一个中文字符代表两个英文字符,输入时要区分长度。比如40个中文,就是80个英文字符。这种需求,EditText 的length属性就不能用了。我查了一下,网上已经有人用EditText filter 实现了。特此记录一下(转载自http://www.voidcn.com/article/p-zlmlmxck-bcd.html):
/**
* Created by chenglin on 2017-3-21.
*/
public class EnglishCharUtils {
int maxLen = 0;
/**
* 输入英文的最大长度 。比如你想要限制40个汉字,80个英文字符,传入的值就是80
* 使用方式:mEdit.setFilters(new InputFilter[]{filter});
*/
public EnglishCharUtils(int len) {
maxLen = len;
}
private EnglishCharUtils() {
}
/**
* 自定义的InputFilter ,用来限制英文中文输入字符限制。两个汉字代表一个英文。
*/
public InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence src, 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 < src.length()) {
char c = src.charAt(sindex++);
if (c < 128) {
count = count + 1;
} else {
count = count + 2;
}
}
if (count > maxLen) {
sindex--;
}
return src.subSequence(0, sindex);
}
};
}
如果你觉得帮到了你,请给作者打赏一口饭吃: