如何限制 Android EditText 字段中的特殊字符?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/3385631/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 09:58:45  来源:igfitidea点击:

How to restrict special characters from an Android EditText field?

androidandroid-edittext

提问by saravanan palpandi

How to restrict special characters from an Android EditText field?

如何限制 Android EditText 字段中的特殊字符?

回答by alvin

Have you tried adding the android:digits="abcde.....0123456789"attribute? Although the android:digitsspecify 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).

您是否尝试过添加android:digits="abcde.....0123456789"属性?尽管android:digits指定它是一个数字字段,但将其设置为也接受字母和特殊字符对我来说确实有效(在 SDK-7 上测试)。

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

如果这不起作用,那么你必须实现KeyListenerhttp: //developer.android.com/reference/android/widget/TextView.html#setKeyListener(android.text.method.KeyListener)

回答by Arun

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

只需将 EditText 对象传递给此方法。还要在变量 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 });

     }

回答by Ashwin

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

我在回答中解决了这个问题:防止 EditText 中的特殊符号。您可以根据需要更改正则表达式。

回答by Sumudu Sahan Weerasuriya

Just put below xml line inside edittext block.

只需将下面的 xml 行放在 edittext 块中。

android:digits="abc"

This will allow to enter only a,b and c characters.

这将只允许输入 a、b 和 c 字符。