第一种方法:
private Context context;
/**
* limit EditText max length
* @param length
*/
public void setInputMaxLength(int length) {
InputFilter[] filters = { new NameLengthFilter(length) };
new EditText(context).setFilters(filters);
}
private class NameLengthFilter implements InputFilter {
int MAX_EN;// 最大英文/数字长度 一个汉字算两个字母
String regEx = "[\\u4e00-\\u9fa5]"; // unicode编码,判断是否为汉字
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) {
// Toast.makeText(MainActivity.this, getString(R.string.count),
// Toast.LENGTH_SHORT).show();
return "";
} 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;
}
}
第二种方法:
edtContent --------表示要输入限制的EditText
/**
* 设置最大输入字符数
* @param lenght
*/
public void setMaxLenght(int length){
if(edtContent != null && length> 0 ){
maxLenght = lenght;
edtContent.setFilters(new InputFilter[]{new InputFilter.LengthFilter(lenght)});
}
}