限制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);
}
}
}
posted @ 2016-12-01 17:27  吴添龙  阅读(1193)  评论(0编辑  收藏  举报