思路:中文占一个长度,英文占0.5个长度(同时符号区分中英文)。
步骤:
1.EditText添加监听是事件
2.在onTextChanged()方法中计算长度
具体代码如下:
editText.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
int contentlength = (int) Math.round(contentLength(s));
if (contentlength>30){//截取,最大长度为30,超过30截取
CharSequence charSequence=s.subSequence(0,start);
editText.setText(charSequence);
Editable editable = editText.getText();
int selEndIndex = editable.length();
Selection.setSelection(editable, selEndIndex);//光标移动到末尾
}
}
@Override
public void afterTextChanged(Editable s) {
}
});
计算长度
public double contentLength(CharSequence str) {
double len = 0;
for (int i = 0; i < str.length(); i++) {
int temp = str.charAt(i);
if (temp < 127 && temp > 0) {
len += 0.5;
} else {
len++;
}
}
return len;
}