有时需要对编辑框EditText限制输入的最大字符数或中文的个数,如下是一段不错的参考代码。
可参考此代码如 法炮制出自己想要的逻辑功能。
myEditText.addTextChangedListener(new TextWatcher() {@Override
public void onTextChanged(CharSequence s, int start, int count, int after) {int mTextMaxlenght = 0;
Editable editable = myEditText.getText();
String str = editable.toString().trim();
int selEndIndex = Selection.getSelectionEnd(editable);
for (int i = 0; i char charAt = str.charAt(i);
if (charAt >&#61; 32 && charAt <&#61; 122) {
mTextMaxlenght&#43;&#43;;
} else {
mTextMaxlenght &#43;&#61; 2;
}
if (mTextMaxlenght > 40) {
String newStr &#61; str.substring(0, i);
myEditText.setText(newStr);
editable &#61; myEditText.getText();
int newLen &#61; editable.length();
if (selEndIndex > newLen) {
selEndIndex&#61;editable.length();
}
Selection.setSelection(editable, selEndIndex);
Toast.makeText(MainActivity.this,"最大长度为40个字符或20个汉字&#xff01;",Toast.LENGTH_SHORT).show();
}}
}&#64;Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {}&#64;Override
public void afterTextChanged(Editable s) {}
});}}