EditText 關于輸入限制以及字數限制的問題
最近遇到個奇葩需求,文本輸入框輸入內容時,只能輸入中文,英文和數字,而且還要對輸入字數做限制,中文最多5個,英文數字最多10個,單單一種類型是比較好控制的,但是要是中文英文混合可就不好判斷了
下面是解決方案:
editText.addTextChangedListener(new TextWatcher() {
String imputtxt;
String str;
@Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (!TextUtils.isEmpty(s)){
remove_text.setVisibility(View.VISIBLE);
}else if (TextUtils.isEmpty(s)){
remove_text.setVisibility(View.GONE);
}
imputtxt = editText.getText().toString();
str = stringFilter(imputtxt);
}
@Override
public void afterTextChanged(Editable s) {
if (!TextUtils.isEmpty(str)){
String limtxt = getLimitSubstring(str);
if (!TextUtils.isEmpty(limtxt)){
if (!limtxt.equals(imputtxt)){
editText.setText(limtxt);
editText.setSelection(limtxt.length());
}
}
}
}
});
我是設置輸入監聽 TextWatcher 在onchange的時候 去檢驗文本輸入的類型利用正則,在afterchange 時候去限制字數長度
//校驗輸入類型
public static String stringFilter(String str)throws PatternSyntaxException {
// 僅僅同意字母、數字和漢字
String regEx = "[^a-zA-Z0-9\u4E00-\u9FA5]";
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(str);
return m.replaceAll("").trim();
}
//限制字符長度
private String getLimitSubstring(String inputStr) {
int orignLen = inputStr.length();
int resultLen = 0;
String temp = null;
for (int i = 0; i < orignLen; i++) {
temp = inputStr.substring(i, i + 1);
try {// 3 bytes to indicate chinese word,1 byte to indicate english
// word ,in utf-8 encode
if (temp.getBytes("utf-8").length == 3) {
resultLen += 2;
} else {
resultLen++;
}
} catch (UnsupportedEncodingException e) {
e.printStackTrace();
}
if (resultLen > 10) {
return inputStr.substring(0, i);
}
}
return inputStr;
}