8

I am currently using

android:digits="qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM "

in android XML in EditText and it is working perfectly. The user can enter only characters from a-z,A-Z and space(I don't want to allow the user to enter numbers or special characters). I would like to add this property to another Edit Text field programaticaly. Can anyone help me to add the above property programmaticaly. I have referred the following links but its of no use

Change android:digits programmatically How to block special characters in androids editText? no ANDROID:DIGITS

if I use

edtTxt.setKeyListener(DigitsKeyListener.getInstance("qwertzuiopasdfghjklyxcvbnmQWERTZUIOPASDFGHJKLYXCVBNM"));

numeric keypad is getting opened.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Anudeep
  • 1,520
  • 1
  • 19
  • 38

1 Answers1

7

Try the code below

edtTxt.setInputType(InputType.TYPE_CLASS_TEXT);
        edtTxt.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 "";
                    }
                }
        });
Febi M Felix
  • 2,799
  • 1
  • 10
  • 13
  • I have done it just before you have posted the answer. However as it works. I have accepted the answer :) – Anudeep Jan 04 '16 at 08:41
  • 1
    This is not the actual answer to the question, this seems like a hacky way, DigitsKyeListener should be able to do the work what is expected with `android:digits` property. – Aseem Sharma Apr 25 '19 at 19:32