编辑
如果您只想设置字母,那么您可以使用 InputFilter 而不是数字。digit
从您的布局中删除此标签。
这是可以帮助您的示例:
edittext.setFilters(new InputFilter[] {
new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
if(src.equals("")){ // for backspace
return src;
}
if(src.toString().matches("[a-zA-Z ]+")){
return src;
}
return "";
}
}
});
试试这个。它经过我自己的测试并像魅力一样工作
editText.setFilters(new InputFilter[]{new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
boolean keepOriginal = true;
StringBuilder sb = new StringBuilder(end - start);
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (isCharAllowed(c)) // put your condition here
sb.append(c);
else
keepOriginal = false;
}
if (keepOriginal)
return null;
else {
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(sb);
TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
return sp;
} else {
return sb;
}
}
}
private boolean isCharAllowed(char c) {
Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
Matcher ms = ps.matcher(String.valueOf(c));
return ms.matches();
}
}});
带 MaxLength 的输入过滤器
使用 InputFilter 时,EditText 的属性被覆盖,然后您可以使用 InputFiler 的最大长度。
试试这个
InputFilter[] inputFilters = new InputFilter[2];
inputFilters[0] = new InputFilter() {
@Override
public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
boolean keepOriginal = true;
StringBuilder sb = new StringBuilder(end - start);
for (int i = start; i < end; i++) {
char c = source.charAt(i);
if (isCharAllowed(c)) // put your condition here
sb.append(c);
else
keepOriginal = false;
}
if (keepOriginal)
return null;
else {
if (source instanceof Spanned) {
SpannableString sp = new SpannableString(sb);
TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
return sp;
} else {
return sb;
}
}
}
private boolean isCharAllowed(char c) {
Pattern ps = Pattern.compile("^[a-zA-Z ]+$");
Matcher ms = ps.matcher(String.valueOf(c));
return ms.matches();
}
};
inputFilters[1] = new InputFilter.LengthFilter(12);
editText.setFilters(inputFilters);