- 原理是通过截取输入的字符串来限制输入的字数 并进行友好提示
public static void linitEditLenth(Context context, EditText editText, int maxLen, String toast) {
Editable editable = editText.getText();
int len = editable.length();
if (len > maxLen) {
KKKKK.showToast(context, toast + "最多只能输入" + maxLen + "个字符");
int selEndIndex = Selection.getSelectionEnd(editable);
String str = editable.toString();
//截取新字符串
String newStr = str.substring(0, maxLen);
editText.setText(newStr);
editable = editText.getText();
//新字符串的长度
int newLen = editable.length();
//旧光标位置超过字符串长度
if (selEndIndex > newLen) {
selEndIndex = editable.length();
}
//设置新光标所在的位置
Selection.setSelection(editable, selEndIndex);
}
}
一行代码搞定
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(5)});