Edittext 只允许字母(以编程方式)
Edittext only allow letters (programmatically)
我正在尝试获得一个只允许字母(小写和大写)的 editTextview。
它适用于此代码:
edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
问题是我的数字键盘是这样的:
要返回普通键盘,我找到了这段代码:
edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
edittv.setInputType(InputType.TYPE_CLASS_TEXT);
它可以恢复键盘,但随后又允许使用所有字符,因此它撤消了之前的代码。
那么,我怎样才能以编程方式只允许使用字母键盘的字母。
这里您使用的是 DigitsKeyListener
extends NumberKeyListener
,它只允许数字,这就是您收到该错误的原因。
这是我针对您的要求的解决方案,在您的 XML.
中使用此行
<EditText
android:id="@+id/edt_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "/>
注意 :- Space 在数字的末尾给出,让用户输入 space 也
以编程方式:-
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 "";
}
}
});
您可以使用下面的代码:
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 });
我正在尝试获得一个只允许字母(小写和大写)的 editTextview。
它适用于此代码:
edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
问题是我的数字键盘是这样的:
要返回普通键盘,我找到了这段代码:
edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
edittv.setInputType(InputType.TYPE_CLASS_TEXT);
它可以恢复键盘,但随后又允许使用所有字符,因此它撤消了之前的代码。
那么,我怎样才能以编程方式只允许使用字母键盘的字母。
这里您使用的是 DigitsKeyListener
extends NumberKeyListener
,它只允许数字,这就是您收到该错误的原因。
这是我针对您的要求的解决方案,在您的 XML.
中使用此行 <EditText
android:id="@+id/edt_username"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Username"
android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "/>
注意 :- Space 在数字的末尾给出,让用户输入 space 也
以编程方式:-
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 "";
}
}
});
您可以使用下面的代码:
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 });