我正在尝试获取只允许使用字母(小写和大写)的editTextview。
它与以下代码配合使用:
edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
问题是我得到了这样的数字键盘:
要回到普通键盘,我找到了以下代码:
edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
edittv.setInputType(InputType.TYPE_CLASS_TEXT);
它可以使键盘恢复原状,但随后又允许所有字符,因此撤消了先前的代码。
所以,我怎么只能以编程方式只允许使用字母键盘的字母。
答案 0 :(得分:3)
您可以在下面使用此代码:
InputFilter filter = new InputFilter() {
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
for (int i = start; i < end; i++) {
if (!Character.isLetter(source.charAt(i))&&!Character.isSpaceChar(source.charAt(i))) {
return "";
}
}
return null;
}
};
edit.setFilters(new InputFilter[] { filter });
答案 1 :(得分:1)
在这里,您使用的是DigitsKeyListener
扩展了NumberKeyListener
,这仅允许数字,这就是为什么您遇到此错误。
这是我为您提供的解决方案,请在您的XML中使用此行。
<EditText
android:id="@+id/edt_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "/>
注意:-数字末尾有空格,用户也可以输入空格
以编程方式:-
edittv.setInputType(InputType.TYPE_CLASS_TEXT);
edittv.setFilters(new InputFilter[]{
new InputFilter() {
public CharSequence filter(CharSequence src, int start,
int end, Spanned dst, int dstart, int dend) {
if (src.equals("")) {
return src;
}
if (src.toString().matches("[a-zA-Z ]+")) {
return src;
}
return "";
}
}
});