How do I use InputFilter to limit characters in an EditText in Android?

后端 未结 20 1668
慢半拍i
慢半拍i 2020-11-22 04:23

I want to restrict the chars to 0-9, a-z, A-Z and spacebar only. Setting inputtype I can limit to digits but I cannot figure out the ways of Inputfilter looking through the

20条回答
  •  野的像风
    2020-11-22 05:05

    This simple solution worked for me when I needed to prevent the user from entering empty strings into an EditText. You can of course add more characters:

    InputFilter textFilter = new InputFilter() {
    
    @Override
    
    public CharSequence filter(CharSequence c, int arg1, int arg2,
    
        Spanned arg3, int arg4, int arg5) {
    
        StringBuilder sbText = new StringBuilder(c);
    
        String text = sbText.toString();
    
        if (text.contains(" ")) {    
            return "";   
        }    
        return c;   
        }   
    };
    
    private void setTextFilter(EditText editText) {
    
        editText.setFilters(new InputFilter[]{textFilter});
    
    }
    

提交回复
热议问题