Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to restrict special characters from an Android EditText field?

How to restrict special characters from an Android EditText field?

like image 359
saravanan palpandi Avatar asked Aug 02 '10 06:08

saravanan palpandi


2 Answers

Have you tried adding the android:digits="abcde.....0123456789" attribute? Although the android:digits specify that it is a numeric field, it does work for me to set it to accept letters as well, and special characters as well (tested on SDK-7).

If this doesn't work then you'll have to implement KeyListener see: http://developer.android.com/reference/android/widget/TextView.html#setKeyListener(android.text.method.KeyListener)

like image 54
alvin Avatar answered Sep 18 '22 14:09

alvin


Just pass the EditText object to this method. Also add the values that is to be blocked in the variable blockCharacterSet.

private void disableSpecialChar(EditText editText) {       final String blockCharacterSet = "<>";        InputFilter filter = new InputFilter() {         @Override        public CharSequence filter(CharSequence source, int start, int end,          Spanned dest, int dstart, int dend) {          if (source != null && blockCharacterSet.contains(("" + source))) {          return "";         }         return null;        }       };        editText.setFilters(new InputFilter[] { filter });       } 
like image 26
Arun Avatar answered Sep 16 '22 14:09

Arun