Edittext仅允许字母(以编程方式) [英] Edittext only allow letters (programmatically)

查看:105
本文介绍了Edittext仅允许字母(以编程方式)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试获取只允许使用字母(小写和大写)的editTextview.

I'm trying to get an editTextview that only allows letters (lower- and uppercase).

它与以下代码配合使用:

It works with this code:

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

问题是我得到了这样的数字键盘:

The problem is that I get a numerical keyboard like this:

要回到普通键盘,我找到了以下代码:

To go back to a normal keyboard I found this code:

edittv.setKeyListener(DigitsKeyListener.getInstance("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ"));
edittv.setInputType(InputType.TYPE_CLASS_TEXT);

它可以使键盘恢复原状,但随后又允许所有字符,因此撤消了先前的代码.

It works for getting the keyboard back but then all characters are allowed again, so it undo's the previous code.

所以,我怎么只能以编程方式只允许使用字母键盘的字母.

So, how can I only allow letters with an alphabetical keyboard programatically.

推荐答案

您可以在下面使用此代码:

You can use this code below:

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 });

这篇关于Edittext仅允许字母(以编程方式)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆