public class MaxLengthWatcher implements TextWatcher{
private int maxLen = 0;
private EditText editText;
public MaxLengthWatcher(int maxLen, EditText editText) {
this.maxLen = maxLen;
this.editText = editText;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
Editable editable = editText.getText();
int len = editable.length();
if (len > 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);
Toast.makeText(mContext, "最多输入" + maxLen + "个字符", Toast.LENGTH_SHORT).show();
}
}
}
一个中文算两个字符:
public class MaxLengthWatcher implements TextWatcher {
private int maxLen = 0;
private EditText editText;
private Context mContext;
public MaxLengthWatcher(int maxLen, EditText editText, Context context) {
this.maxLen = maxLen;
this.editText = editText;
mContext = context;
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
@Override
public void afterTextChanged(Editable s) {
try {
Editable editable = editText.getText();
//转成bytes,getBytes("GBK")中一个汉字占两个字节
int len = 0;
len = editable.toString().getBytes("GBK").length;
Timber.e("len: " + len);
if (len > maxLen){
int selEndIndex = Selection.getSelectionEnd(editable);
//避免最后出现半个汉字处理(如果是汉字,byte < 0 (不完全正确,这里应该没问题))
byte[] bytes = editable.toString().getBytes("GBK");
int length;
int count = 0;
for (int i = 0; i < maxLen; i++) {
if (bytes[i] < 0) count++;
}
if ((count % 2) != 0){
length = maxLen - 1;
} else {
length = maxLen;
}
String newStr = new String(Arrays.copyOf(bytes, length), "GBK");
editText.setText(newStr);
editable = editText.getText();
int newLen = editable.length();
if (selEndIndex > newLen){
selEndIndex = editable.length();
}
Selection.setSelection(editable, selEndIndex);
ToastUtils.show(mContext, String.format("最多输入%s个汉字或%s个字符", maxLen / 2, maxLen));
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
} catch (Exception e){
e.printStackTrace();
}
}
}