最近来网上找了一些EditText的输入框监听提示字数限制的小例子 但是没有找到心中想要的 于是自己写了一个 第一次写博客 多有不好 请谅解,来正文吧
首先中英文输入我是既要做一个 中英文识别,识别是不是中文吗?
public static boolean isChinese(char c) {
Character.UnicodeBlock ub = Character.UnicodeBlock.of(c);
if (ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_COMPATIBILITY_IDEOGRAPHS
|| ub == Character.UnicodeBlock.CJK_UNIFIED_IDEOGRAPHS_EXTENSION_A
|| ub == Character.UnicodeBlock.GENERAL_PUNCTUATION
|| ub == Character.UnicodeBlock.CJK_SYMBOLS_AND_PUNCTUATION
|| ub == Character.UnicodeBlock.HALFWIDTH_AND_FULLWIDTH_FORMS) {
return true;
}
return false;
}
当识别了中英文 我就开始对文字进行监听就是真正有用的了
//文字监听事件
editText.addTextChangedListener(new TextWatcher() {
private CharSequence temp;
private boolean isEdit = true;
private int selectionStart;
private int selectionEnd;
public void beforeTextChanged(CharSequence s, int arg1, int arg2,int arg3) {
temp = s;}
@Override
public void onTextChanged(CharSequence s, int arg1, int arg2,int arg3) {
}
@Override
public void afterTextChanged(Editable s) {
//获取开头下标
selectionStart = editText.getSelectionStart();
//获取结尾下标
selectionEnd = editText.getSelectionEnd();
Log.i("gongbiao1", "" + selectionStart);
Log.i("gongbiao", "" + temp);
byte[] bytes = new byte[0];
//转化成字节
bytes = temp.toString().getBytes();
//获取字节的长度
int bLength = bytes.length;
//获取字符串的长度
int zLenght = temp.length();
//如果字节的长度和字符串的长度相等说明是纯英文
if (bLength == zLenght) {
//超过20个字符
if (temp.length() > 20) {
Toast.makeText(MainActivity.this,"您输入的字数已上限!", Toast.LENGTH_SHORT).show();
//删除刚刚输入的文字
s.delete(selectionStart - 1, selectionEnd);
int tempSelection = selectionStart;
//写入文本框
editText.setText(s);
//下标移到开头
editText.setSelection(tempSelection);
}
} else {
//一个汉字等于两个字节,但是随着编码改变汉字可能等于3个字节或者更多
//次编译环境下是3个字节
if (bLength == zLenght * 3 || bLength == zLenght * 2) {
if (temp.length() > 10) {
Toast.makeText(MainActivity.this,"您输入的字数已上限!", Toast.LENGTH_SHORT).show();
s.delete(selectionStart - 1, selectionEnd);
int tempSelection = selectionStart;
editText.setText(s);
editText.setSelection(tempSelection);
}
} else {
//中英文混合
numEnglish = 0;
numChinse = 0;
//得出到底有几个中文几个英文
for (int i = 0; i < temp.length(); i++) {
if (!isChinese(temp.charAt(i))) {
numEnglish++;
} else {
numChinse++;
}
}
float result = (float) (numEnglish / 2) + numChinse;
float results = Math.round(result * 10) / 10f;
if (results > 10) {
Toast.makeText(MainActivity.this, "您输入的字数已上限!", Toast.LENGTH_SHORT).show();
s.delete(selectionStart - 1, selectionEnd);
int tempSelection = selectionStart;
editText.setText(s);
editText.setSelection(tempSelection);
}
}
}
}
});
}
第一次写博客 不好别喷 好的话 点个赞吧!!!谢谢!