我正在尝试创建和InputFilter,仅允许用户插入 1 空格和否特殊字符。
我的代码可以在这里找到:https://pastebin.com/L0J1Ua23
@Override
public CharSequence filter(CharSequence charSequence, int i, int i1, Spanned spanned, int i2, int i3) {
int specialCharacters = 0;
// Check if what he has inserted has only
// Letters.
char c;
for (int pos = 0; pos < charSequence.length(); pos++) {
c = charSequence.charAt(pos);
if (!Character.isLetter(c) && !isAcceptedSpecialChar(c)) {
return "";
}
}
for (int pos = i; pos < i1; pos++) {
c = charSequence.charAt(pos);
if (Character.isWhitespace(c)) {
++specialCharacters;
}
}
for (int pos = 0; pos < spanned.length(); pos++) {
c = spanned.charAt(pos);
if (Character.isWhitespace(c)) {
++specialCharacters;
}
}
return specialCharacters > maxWhitespaces ? "" : null;
}
问题在于,每当我插入特殊字符(如“ @”或“-”)时,我的整个文本都会被删除。而且,对于我键入的每个字符,我的InputFilter都会被调用2次(从同一线程)。
将InputFilter附加到视图的方式:
private void setMaxLengthFields() {
InputFilter[] inputFilters1 = new InputFilter[]{new MaxWhitespacesFilter(1)};
firstNameView.setFilters(inputFilters1);
lastNameView.setFilters(inputFilters1);
}
还有其他人有这个问题吗? 还是有人知道解决这个问题的方法?