edittext 禁止输入非法字符和空格,用到输入过滤器InputFilter

一般在我们初始化的时候,给需要限制的edittext直接设置 

//禁止输入空格
setEditTextInhibitInputSpeChat(et_nickname);

//禁止输入空格
    private void setEditTextInhibitInputSpeChat(EditText et_names) {
        InputFilter filter=new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned             
    dest, int dstart, int dend) {
                if(source.equals(" "))
                return "";
                else return null;
            }
        };
        et_names.setFilters(new InputFilter[]{filter});
    }
//禁止输入字符
setEditTextInhibitInputSpeChats(et_username);
//禁止添加非法字符
    private void setEditTextInhibitInputSpeChats(EditText et_name) {
        InputFilter filter=new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                String speChat="[`~!@#$%^&*()+=|{}':;',\\[\\].<>/?~!@#¥%……&*()——+|{}【】‘;:”“’。,、?]";
                Pattern pattern = Pattern.compile(speChat);
                Matcher matcher = pattern.matcher(source.toString());
                if(matcher.find())
                    return "";
                else return null;
            }
        };

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

    }

 

你可能感兴趣的:(知识总结)