我想限制用戶以編程方式輸入特殊字符&空間。 下面是我在按下空格鍵就刪除最後一個字符代碼以編程方式限制特殊字符和空格
InputFilter[] alphaNumericFilter = new InputFilter[2];
alphaNumericFilter[0] = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int k = start; k < end; k++) {
boolean isLetterOrDigit = Character.isLetterOrDigit(source.charAt(k));
boolean isSpaceChar = Character.isSpaceChar(source.charAt(k));
if ((source.length() > 0 && isSpaceChar) ||
(!isLetterOrDigit && !isSpaceChar) ||
(isSpaceChar && TextUtils.isEmpty(dest))) {
return "";
}
}
return null;
}
};
。根據您的要求,如
public static InputFilter getAlphaNumericInputFilter(){
return new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if(source.equals("")){ // for backspace
return source;
}
if(source.toString().matches("[a-zA-Z0-9 ]+")){
return source;
}
return "";
}
};
}
在這裏如果你只是改變相匹配的字符串:
請問您可以澄清什麼是您的edittext可接受的輸入是(a-z A-Z 0-9)還是有些別的 –