我想通过输入过滤器以编程方式执行此操作,而不是像xml中那样 - android:digits =" aA"。
这是我的代码
public static void RemoveCharacter(EditText text, String character, int length) {
final String blockCharacterSet = character;
// final String blockCharacterSet = "\"+[]&~#^|$%*!@/()-'\\\":;,?{}=!$^';,?×÷<>{}€£¥₩%~`¤♡♥_|《》¡¿°•○●□■◇◆♧♣▲▼▶◀↑↓←→☆★▪:-);-):-D:-(:'(:O\";
InputFilter[] filter1 = new InputFilter[2];
filter1[0] = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source != null && blockCharacterSet.contains(("" + source))) {
return "";
}
return null;
}
};
filter1[1] = new InputFilter.LengthFilter(length);
text.setFilters(filter1);
}
它完全适用于Moto G,nexus设备但不适用于三星设备。
答案 0 :(得分:1)
尝试使用以下代码添加您选择的输入类型,它将起作用:
your_editText.setInputType(InputType.TYPE_CLASS_TEXT |
InputType.TYPE_TEXT_VARIATION_PASSWORD);
答案 1 :(得分:1)
好吧,如果你真的想用InputFilter
做这件事,那将会比这更复杂。
不同的键盘行为方式完全不同,所以我的猜测是你的解决方案不能使用Swype / Swift键盘。
可能尝试使用这样的东西:
final Set<Character> blockSet = new HashSet<>();
blockSet.addAll(Arrays.asList('1', '2', '3', '4','5', '6', '7', '8', '9', '0'));
InputFilter filter = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (Character.isDigit(source.charAt(i))) {
char[] v = new char[end - start];
TextUtils.getChars(source, start, end, v, 0);
String s = new String(v);
if (source instanceof Spanned) {
CharSequence sp = new SpannableString(s);
TextUtils.copySpansFrom((Spanned) source,
start, end, null, (Spannable) sp, 0);
boolean containsDigit = true;
while (containsDigit) {
containsDigit = false;
for (int j = 0; j < sp.length(); j++) {
if (blockSet.contains(sp.charAt(j))) {
sp = TextUtils.concat(sp.subSequence(0, j), sp.subSequence(j + 1, sp.length()));
containsDigit = true;
break;
}
}
}
return sp;
} else {
s = s.replaceAll("\\d", "");
return s;
}
}
}
return null; // keep original
}
};