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

后端 未结 20 1181
慢半拍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:16

    For some reason the android.text.LoginFilter class's constructor is package-scoped, so you can't directly extend it (even though it would be identical to this code). But you can extend LoginFilter.UsernameFilterGeneric! Then you just have this:

    class ABCFilter extends LoginFilter.UsernameFilterGeneric {
        public UsernameFilter() {
            super(false); // false prevents not-allowed characters from being appended
        }
    
        @Override
        public boolean isAllowed(char c) {
            if ('A' <= c && c <= 'C')
                return true;
            if ('a' <= c && c <= 'c')
                return true;
    
            return false;
        }
    }
    

    This isn't really documented, but it's part of the core lib, and the source is straightforward. I've been using it for a while now, so far no problems, though I admit I haven't tried doing anything complex involving spannables.

提交回复
热议问题