在開發過程會根據實際情況對輸入框中的輸入內容加以限制,限制輸入內容不同對應的策略不同
在實際開發過程中遇到輸入框中只允許輸入漢字的要求,針對該問題的解決方案如下:
setFilters接收的參數是InputFilter類型的數組,通過該方法對輸入的文字進行過濾
mEditText.setFilters(filter);
private InputFilter[] filter = new InputFilter[]{
new InputFilter() {
@Override
public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
if (!checkNameChese(charSequence.toString())) {
return "";
}
return null;
}
}
};
/**
* 檢測String是否全是中文
*
* @param name
* @return
*/
public boolean checkNameChese(String name) {
boolean res = true;
char[] cTemp = name.toCharArray();
for (int i = 0; i < name.length(); i++) {
if (!isChinese(cTemp[i])) {
res = false;
break;
}
}
return res;
}
/**
* 判定輸入漢字
* @param c
* @return
*/
public 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
) {
return true;
}
return false;
}
針對輸入框中只能輸入字母或數字的情況,對應的策略如下:
mEditText.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) {
String editable = mEditText.getText().toString();
String regEx = "[^a-zA-Z0-9]"; //只能輸入字母或數字
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(editable);
String str = m.replaceAll("").trim(); //刪除不是字母或者數字的字符
if (TextUtils.equals(str, mEditText.getText().toString())) {
mEditText.setText(str);
mEditText.setSelection(str.length()); //重新設置光標的所在位置
}
@Override
public void afterTextChanged(Editable s) {
}
});