EditText and InputFilter cause repeating text

前端 未结 5 1945
野性不改
野性不改 2021-02-19 05:43

I\'m trying to implement an EditText that limits input to alpha chars only [A-Za-z].

I started with the InputFilter method from this post. When I type \"a%\" the text d

5条回答
  •  你的背包
    2021-02-19 06:05

    Fix for repeating text, work on all Android Versions:

    public static InputFilter getOnlyCharactersFilter() {
        return getCustomInputFilter(true, false, false);
    }
    
    public static InputFilter getCharactersAndDigitsFilter() {
        return getCustomInputFilter(true, true, false);
    }
    
    public static InputFilter getCustomInputFilter(final boolean allowCharacters, final boolean allowDigits, final boolean allowSpaceChar) {
        return new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                boolean keepOriginal = true;
                StringBuilder sb = new StringBuilder(end - start);
                for (int i = start; i < end; i++) {
                    char c = source.charAt(i);
                    if (isCharAllowed(c)) {
                        sb.append(c);
                    } else {
                        keepOriginal = false;
                    }
                }
                if (keepOriginal) {
                    return null;
                } else {
                    if (source instanceof Spanned) {
                        SpannableString sp = new SpannableString(sb);
                        TextUtils.copySpansFrom((Spanned) source, start, sb.length(), null, sp, 0);
                        return sp;
                    } else {
                        return sb;
                    }
                }
            }
    
            private boolean isCharAllowed(char c) {
                if (Character.isLetter(c) && allowCharacters) {
                    return true;
                }
                if (Character.isDigit(c) && allowDigits) {
                    return true;
                }
                if (Character.isSpaceChar(c) && allowSpaceChar) {
                    return true;
                }
                return false;
            }
        };
    }
    

    Now you can use this filer like:

     //Accept Characters Only
    edit_text.setFilters(new InputFilter[]{getOnlyCharactersFilter()});
    
    //Accept Digits and Characters
    edit_text.setFilters(new InputFilter[]{getCharactersAndDigitsFilter()});
    
    //Accept Digits and Characters and SpaceBar
    edit_text.setFilters(new InputFilter[]{getCustomInputFilter(true,true,true)});
    

提交回复
热议问题