Edittext only allow letters (programmatically)

Daan Seuntjens :

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:

keyboard example

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.

bhumilvyas :

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

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=114009&siteId=1