/**
* EditText字符数限制
* (中文及中文字符算两个字符,英文及英文字符算两个字符)
*/
public class EditTextLengthHelper {
static EditTextLengthHelper instance;
private EditTextLengthHelper() {
}
public static EditTextLengthHelper getInstance() {
if (null == instance) {
synchronized (EditTextLengthHelper.class) {
if (null == instance) {
instance = new EditTextLengthHelper();
}
}
}
return instance;
}
/**
* 设置EditText的字数限制
*
* @param textLength 需要限制的字符数量
* @return
*/
public InputFilter lengthResult(int textLength) {
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence src, int start, int end, Spanned dest, int dstart, int dend) {
int dindex = 0;
int count = 0;
while (count <= textLength && dindex < dest.length()) {
char c = dest.charAt(dindex++);
//这里是根据ACSII值进行判定的中英文,其中中文及中文符号的ACSII值都是大于128的
if (c <= 128) {
count = count + 1;
} else {
count = count + 2;
}
}
if (count > textLength) {
return dest.subSequence(0, dindex - 1);
}
int sindex = 0;
while (count <= textLength && sindex < src.length()) {
char c = src.charAt(sindex++);
if (c < 128) {
count = count + 1;
} else {
count = count + 2;
}
}
if (count > textLength) {
sindex--;
}
return src.subSequence(0, sindex);
}
};
return filter;
}
/**
* 我需要做的是带有字数统计的所以会出现以下代码,
* 如果需求不需要有字数限制(例如微信设置昵称只是有字符数量的限制并没有字符数量的统计)
* 那么这段代码可以忽略
*
*/
/**
* EditText输入,统计字数改变
* (中文及中文字符算两个字符,英文及英文字符算一个字符)
*
* @param mEditText
* @return
*/
public int editTextNum(EditText mEditText) {
int mTextMaxlenght = 0;
Editable editable = mEditText.getText();
String str = editable.toString();
int selEndIndex = Selection.getSelectionEnd(editable);
for (int i = 0; i < str.length(); i++) {
char charAt = str.charAt(i);
if (charAt <= 128) {
mTextMaxlenght++;
} else {
mTextMaxlenght += 2;
}
if (mTextMaxlenght > 24) {
String newStr = str.substring(0, i);
mEditText.setText(newStr);
editable = mEditText.getText();
int newLen = editable.length();
if (selEndIndex > newLen) {
selEndIndex = editable.length();
}
}
}
Selection.setSelection(editable, selEndIndex);
return mTextMaxlenght;
}
以上是实现该功能所需要的代码,现在我们来说以下用法,其实很简单,就是在EditText的addTextChangedListener监听中的onTextChanged方法中进行操作
示例:
mEditNickName.addTextChangedListener(new TextWatcher() {
@Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
@RequiresApi(api = Build.VERSION_CODES.N)
@Override
public void onTextChanged(CharSequence charSequence, int start, int before, int count) {
//其中这一行代码就是实现该功能的调用,因为我们需求是限制24个字符所以这里我传了一个24进去
mTextNickNameNum.setText(EditTextLengthHelper.getInstance().editTextNum(mEditNickName) + "/24");
}
@Override
public void afterTextChanged(Editable editable) {
}
});
至此,该功能就已经介绍完毕。现在我来回顾一下EditText的addTextChangedListener监听中的onTextChanged方法,以此作为自己使用的参考
还以上述代码为例::其中
//charSequence 参数的意义为 输入框中改变后的字符串信息
//start 参数的意义为 输入框中改变后的字符串的起始位置
//before 参数的意义为 输入框中改变前的字符串的位置 默认为0
//count 参数的意义为 输入框中改变后的一共输入字符串的数量
这就是今天我要分享给大家的内容,希望各大神勿喷