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

后端 未结 20 1136
慢半拍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 04:52

    Ignoring the span stuff that other people have dealt with, to properly handle dictionary suggestions I found the following code works.

    The source grows as the suggestion grows so we have to look at how many characters it's actually expecting us to replace before we return anything.

    If we don't have any invalid characters, return null so that the default replacement occurs.

    Otherwise we need to extract out the valid characters from the substring that's ACTUALLY going to be placed into the EditText.

    InputFilter filter = new InputFilter() { 
        public CharSequence filter(CharSequence source, int start, int end, 
        Spanned dest, int dstart, int dend) { 
    
            boolean includesInvalidCharacter = false;
            StringBuilder stringBuilder = new StringBuilder();
    
            int destLength = dend - dstart + 1;
            int adjustStart = source.length() - destLength;
            for(int i=start ; i= adjustStart)
                         stringBuilder.append(sourceChar);
                } else
                    includesInvalidCharacter = true;
            }
            return includesInvalidCharacter ? stringBuilder : null;
        } 
    }; 
    

提交回复
热议问题