Search code examples
javaandroidandroid-edittextkeyboard

Edittext only allow letters (programmatically)


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.


Solution

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