限制特殊字符&以编程方式

时间:2017-04-17 11:13:37

标签: android android-edittext android-input-filter

我想限制用户输入特殊字符&空间编程。 以下是我的代码

InputFilter[] alphaNumericFilter = new InputFilter[2];
        alphaNumericFilter[0] = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int k = start; k < end; k++) {
                    boolean isLetterOrDigit = Character.isLetterOrDigit(source.charAt(k));
                    boolean isSpaceChar = Character.isSpaceChar(source.charAt(k));
                    if ((source.length() > 0 && isSpaceChar) ||
                            (!isLetterOrDigit && !isSpaceChar) ||
                            (isSpaceChar && TextUtils.isEmpty(dest))) {
                        return "";
                    }
                }
                return null;
            }
        };

按空格键删除最后一个字符。

4 个答案:

答案 0 :(得分:1)

使用此代码过滤您的edittext

 private String yourCharacterThatYouWantToBlock= " ~#^|$%&*!";

        private InputFilter filter = new InputFilter() {

            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {

                if (source != null && yourCharacterThatYouWantToBlock.contains(("" + source))) {
                    return "";
                }
                return null;
            }
        };
  

现在将此过滤器应用于您的edittext。

 yourEditText.setFilters(new InputFilter[] { filter });

答案 1 :(得分:0)

你可以这样做:

public static InputFilter getAlphaNumericInputFilter(){
        return new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end,
                                       Spanned dest, int dstart, int dend) {

                if(source.equals("")){ // for backspace
                    return source;
                }
                if(source.toString().matches("[a-zA-Z0-9 ]+")){
                    return source;
                }
                return "";
            }
        };
    }

这里如果您可以根据您的要求更改匹配字符串,例如。避免使用字母数字的空间然后应该这样:[a-zA-Z0-9] +。

希望它对你有帮助!

答案 2 :(得分:0)

InputFilter alphaNumericFilter = new InputFilter() {   
     @Override  
     public CharSequence filter(CharSequence arg0, int arg1, int arg2, Spanned arg3, int arg4, int arg5)  
     {  
         for (int k = arg1; k < arg2; k++) {   
             if (!Character.isLetterOrDigit(arg0.charAt(k))) {   
             return ""; 
             }  
         }
         return null;
     }  
 };   
 mFirstName.setFilters(new InputFilter[]{ alphaNumericFilter});   

答案 3 :(得分:-2)

最后,我通过在代码中添加以下行来解决此问题

mEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);

此行不会在键盘上显示建议。