Edittext只允许字母(程序控制)

3

我想获得一个只允许字母(大写和小写)输入的editTextview。

使用以下代码可以实现:

 edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));

问题在于我得到了一个数字键盘,就像这样:

keyboard example

为了返回到正常的键盘,我找到了这个代码:
edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
edittv.setInputType(InputType.TYPE_CLASS_TEXT);

它可以恢复键盘,但随后所有字符都被允许,因此它撤消了先前的代码。

那么,我怎样才能通过编程仅允许字母使用字母键盘呢?


如果我切换它们,那么只有字母再次被允许,这很好,但我又得到了一个数字键盘。 - Daan Seuntjens
@DaanSeuntjens 我更新了我的答案,请查看。 - Parth Lotia
2个回答

6
您可以使用下面的代码:
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 });

3

您正在使用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 "";
                }
            }
    });

TextView是通过代码动态创建的,因此不能使用XML。 - Daan Seuntjens
看起来是正确的,但我会检查@bhumilvyas的答案,因为他首先使用了setFilter。我选择给你点赞,因为这也是一个正确的答案,希望你能理解。 - Daan Seuntjens

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接