3

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.

Daan Seuntjens
  • 880
  • 1
  • 18
  • 37

2 Answers2

6

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 });
bhumilvyas
  • 121
  • 5
3

Here you are using DigitsKeyListener extends NumberKeyListener which only allows numbers thats why you were getting that error.

Here is my solution for your requirements use this lines in your XML.

  <EditText
        android:id="@+id/edt_username"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:hint="Username"
        android:digits="abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ "/>

Note :- Space is given at the end of digits for let user input space also

For Programmatically :-

    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 "";
                }
            }
    });
Parth Lotia
  • 753
  • 1
  • 7
  • 25
  • The textview is created dynamically using code so using xml isn't an option. – Daan Seuntjens Mar 05 '19 at 12:47
  • It seems correct but I will check @bhumilvyas answer because he was first with an answer using setFilter. I upvoted you instead because it is aswell a wright answer, hope you understand. – Daan Seuntjens Mar 05 '19 at 13:05