How to exclude special characters from android keypad for EditText

Jes picture Jes · Sep 7, 2011 · Viewed 19.5k times · Source

Hi I want to show only numbers and characters on the keypad for EditText in android, I did try to add the attribute android:inputType = text|number but it did not work.

Please help me with any other better suggestion. thanks in advance.

Answer

Aju picture Aju · Sep 7, 2011

Use the filter for that. Here I am adding the code for filter.

EditText etName = (EditText)findViewById(R.id.etName);
InputFilter filter = new InputFilter() { 
            @Override
            public CharSequence filter(CharSequence source, int start, int end, 
                            Spanned dest, int dstart, int dend) { 
                    for (int i = start; i < end; i++) { 
                            if (!Character.isLetterOrDigit(source.charAt(i))) { 
                                    return ""; 
                            } 
                    } 
                    return null; 
            }
};
etName.setFilters(new InputFilter[]{filter});