How to restrict special characters from an Android EditText field?

与世无争的帅哥 提交于 2019-12-17 16:27:14

问题


How to restrict special characters from an Android EditText field?


回答1:


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)




回答2:


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

     }



回答3:


I have solved this problem in my answer: Prevent special symbols in EditText. You can change the regex as per your requirement.



来源:https://stackoverflow.com/questions/3385631/how-to-restrict-special-characters-from-an-android-edittext-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!