private Context context;
private EditText editText;
private int maximum;
public void setWordNumber(Context context, EditText editText, int maximum) {
this.context = context;
this.editText = editText;
this.maximum = maximum;
//设置监听器 监听EditText 的变化
editText.addTextChangedListener(mTextWatcher);
}
private TextWatcher mTextWatcher = new TextWatcher() {
private int editStart;
private int editEnd;
public void afterTextChanged(Editable s) {
editStart = editText.getSelectionStart();
editEnd = editText.getSelectionEnd();
// 先去掉监听器,否则会出现栈溢出
editText.removeTextChangedListener(mTextWatcher);
// 注意这里只能每次都对整个EditText的内容求长度,不能对删除的单个字符求长度
// 因为是中英文混合,单个字符而言,calculateLength函数都会返回1
while (calculateLength(s.toString()) > maximum) { // 当输入字符个数超过限制的大小时,进行截断操作
s.delete(editStart - 1, editEnd);
editStart--;
editEnd--;
Toast.makeText(context, "最多输入" + maximum + "字", Toast.LENGTH_SHORT).show();
}
editText.setText(s);
editText.setSelection(editStart);
// 恢复监听器
editText.addTextChangedListener(mTextWatcher);
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void onTextChanged(CharSequence s, int start, int before,
int count) {
}
};
//判断字符的长度
private long calculateLength(CharSequence c) {
double len = 0;
for (int i = 0; i < c.length(); i++) {
int tmp = (int) c.charAt(i);
if (tmp > 0 && tmp < 127) {
len += 0.5;
} else {
len++;
}
}
return Math.round(len);
}
android EditText设置最多输入多少个字提示 ,并只取最多的那些字
最新推荐文章于 2022-04-05 13:41:57 发布