16

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 disappears then if I hit backspace the text is "a". I've tried other variations on the filter function like using a regex to match only [A-Za-z] and sometimes see crazy behavior like repeating chars, I'll type "a" then "b" and get "aab" then type "c" and get "aabaabc" then hit backspace and get "aabaabcaabaabc"!

Here's the code I'm working with so far with the different approaches I've tried.

    EditText input = (EditText)findViewById( R.id.inputText );
    InputFilter filter = new InputFilter() {
        @Override
        public CharSequence filter( CharSequence source, int start, int end, Spanned dest, int dstart, int dend ) {
            //String data = source.toString();
            //String ret = null;
            /*
            boolean isValid = data.matches( "[A-Za-z]" );
            if( isValid ) {
                ret = null;
            }
            else {
                ret = data.replaceAll( "[@#$%^&*]", "" );
            }
            */
            /*
            dest = new SpannableStringBuilder();
            ret = data.replaceAll( "[@#$%^&*]", "" );
            return ret;
            */

            for( int i = start; i < end; i++ ) {
                if( !Character.isLetter( source.charAt( i ) ) ) {
                    return "";
                }
            }

            return null;
        }
    };
    input.setFilters( new InputFilter[]{ filter } );

I'm totally stumped on this one so any help here would be greatly appreciated.

EDIT: Ok, I've done quite a lot of experimenting with InputFilter and have drawn some conclusions, albeit no solution to the problem. See the comments in my code below. I'm going to try Imran Rana's solution now.

    EditText input = (EditText)findViewById( R.id.inputText );
    InputFilter filter = new InputFilter() {
        // It is not clear what this function should return!
        // Docs say return null to allow the new char(s) and return "" to disallow
        // but the behavior when returning "" is inconsistent.
        // 
        // The source parameter is a SpannableStringBuilder if 1 char is entered but it 
        // equals the whole string from the EditText.
        // If more than one char is entered (as is the case with some keyboards that auto insert 
        // a space after certain chars) then the source param is a CharSequence and equals only 
        // the new chars.
        @Override
        public CharSequence filter( CharSequence source, int start, int end, Spanned dest, int dstart, int dend ) {
            String data = source.toString().substring( start, end );
            String retData = null;

            boolean isValid = data.matches( "[A-Za-z]+" );
            if( !isValid ) {
                if( source instanceof SpannableStringBuilder ) {
                    // This works until the next char is evaluated then you get repeats 
                    // (Enter "a" then "^" gives "a". Then enter "b" gives "aab")
                    retData = data.replaceAll( "[@#$%^&*']", "" );
                    // If I instead always returns an empty string here then the EditText is blanked.
                    // (Enter "a" then "^" gives "")
                    //retData = "";
                }
                else { // source is instanceof CharSequence
                    // We only get here if more than 1 char was entered (like "& ").
                    // And again, this works until the next char is evaluated then you get repeats 
                    // (Enter "a" then "& " gives "a". Then enter "b" gives "aab")
                    retData = "";
                }
            }

            return retData;
        }
    };
    input.setFilters( new InputFilter[]{ filter } );
4
  • Your code with .replaceAll() is almost correct. The repeated characters you are caused by creating a string with the complete input string in String data = source.toString(), while you should be working on the subset Android is asking about, as in String data = source.toString().substring(start,end) May 29, 2012 at 2:55
  • Seems the problem I'm having here is that start is always 0 when I enter 1 char at a time. Hence String data = source.toString().substring( start, end ); is always giving me the full text and not just what has changed.
    – Rooster242
    May 29, 2012 at 22:59
  • 1
    ...Yep, just tried the sample from this post and start is always 0 so I'm getting repeated chars with it too.
    – Rooster242
    May 29, 2012 at 23:08
  • I tried all the other solutions and finally achieved it. See my answer here Dec 15, 2021 at 7:15

5 Answers 5

5

Use the following code:

EditText input = (EditText) findViewById(R.id.inputText);
   input.addTextChangedListener(new TextWatcher() {

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub
         for( int i = start;i<s.toString().length(); i++ ) {
             if( !Character.isLetter(s.charAt( i ) ) ) {
                input.setText("");
             }
         }

    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }

    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub

    }
   });

If you want the valid text to remain in the EditText:


 input.addTextChangedListener(new TextWatcher() {

    public void onTextChanged(CharSequence s, int start, int before, int count) {
        // TODO Auto-generated method stub

    }

    public void beforeTextChanged(CharSequence s, int start, int count,
            int after) {
        // TODO Auto-generated method stub

    }
    public void afterTextChanged(Editable s) {
        // TODO Auto-generated method stub
         for( int i = 0;i<s.toString().length(); i++ ) {
             if( !Character.isLetter(s.charAt( i ) ) ) {                    
                s.replace(i, i+1,"");               
             }
         }
    }
   });
4
  • This almost works for me. I want the valid text to remain in the EditText. So if I enter "a" then "b" then "^" I want to still see "ab" in the EditText. Of course if I call setText with anything but an empty string it calls onTextChanged infinitely.
    – Rooster242
    May 29, 2012 at 21:43
  • @Rooster242 see my edit, if you want valid text to remain in EditText just add above code to afterTextChanged() method and remove previous code from onTextChanged() method
    – Imran Rana
    May 30, 2012 at 10:06
  • Ah, thanks Imran, works great. Both approaches work actually (InputFilter and TextWatcher) I decided to use TextWatcher since it's a little easier to see what's going on imho and I don't need to use a blacklist in replaceAll(). I'm marking my own answer as the solution though since it was the repeating chars caused by android:cursorVisible="false" that was really tripping me up. I created a bug report for it, Issue 32475.
    – Rooster242
    May 30, 2012 at 21:50
  • Had no luck with InputFilter while TextWatcher works great with IME
    – Tertium
    Oct 17, 2012 at 17:12
4

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)});
1
  • This is a good answer but if you want a more elegant and simple way look at here Dec 15, 2021 at 7:16
1

Bingo, I found the problem!

When I use android:cursorVisible="false" on the EditText the start and dstart parameters don't match up correctly.

The start parameter is still always 0 for me, but the dstart parameter is also always 0 so it works out as long as I use .replaceAll(). This is contrary to what this post says so I don't quite understand why but at least I can build something that works now!

2
1

We had a similar problem and I believe a solution[0] that would work for you as well. Our requirements were to implement an EditText that stripped rich text input. For example, if the user copied bold text to their clipboard and pasted it into the EditText, the EditText should remove the bold emphasis styling and preserve only the plain text.

The solution class looks something like this:

public class PlainEditText extends EditText {
    public PlainEditText(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        addFilter(this, new PlainTextInputFilter());
    }

    private void addFilter(TextView textView, InputFilter filter) {
        InputFilter[] filters = textView.getFilters();
        InputFilter[] newFilters = Arrays.copyOf(filters, filters.length + 1);
        newFilters[filters.length] = filter;
        textView.setFilters(newFilters);
    }

    private static class PlainTextInputFilter implements InputFilter {
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest,
                                   int dstart, int dend) {
            return stripRichText(source, start, end);
        }

        private CharSequence stripRichText(CharSequence str, int start, int end) {
            // ...
        }
    }
}

Our original implementation for stripRichText() was simple:

// -- BROKEN. DO NOT USE --
String plainText = str.subSequence(start, end).toString();
return plainText;

The Java base String class doesn't retain any styling information so converting the CharSequence interface to a concrete String copies only plain text.

What we didn't realize was that some Android soft keyboards add and depend on temporary compositional hints for typos and other things. The problem manifests by removing the hints as well as repeating characters in an unexpected way (usually doubling the entire EditText field's input). The documentation[1] for InputFilter.filter() communicates the requirement this way:

 * Note: If <var>source</var> is an instance of {@link Spanned} or
 * {@link Spannable}, the span objects in the <var>source</var> should be 
 * copied into the filtered result (i.e. the non-null return value). 

I believe the proper solution is to preserve temporary spans:

   /** Strips all rich text except spans used to provide compositional hints. */
    private CharSequence stripRichText(CharSequence str, int start, int end) {
        String plainText = str.subSequence(start, end).toString();
        SpannableString ret = new SpannableString(plainText);
        if (str instanceof Spanned) {
            List<Object> keyboardHintSpans = getComposingSpans((Spanned) str, start, end);
            copySpans((Spanned) str, ret, keyboardHintSpans);
        }
        return ret;
    }

    /**
     * @return Temporary spans, often applied by the keyboard to provide hints such as typos.
     *
     * @see {@link android.view.inputmethod.BaseInputConnection#removeComposingSpans}
     * @see {@link android.inputmethod.latin.inputlogic.InputLogic#setComposingTextInternalWithBackgroundColor}
     */
    @NonNull private List<Object> getComposingSpans(@NonNull Spanned spanned,
                                                    int start,
                                                    int end) {
        // TODO: replace with Apache CollectionUtils.filter().
        List<Object> ret = new ArrayList<>();
        for (Object span : getSpans(spanned, start, end)) {
            if (isComposingSpan(spanned, span)) {
                ret.add(span);
            }
        }
        return ret;
    }

    private Object[] getSpans(@NonNull Spanned spanned, int start, int end) {
        Class<Object> anyType = Object.class;
        return spanned.getSpans(start, end, anyType);
    }

    private boolean isComposingSpan(@NonNull Spanned spanned, Object span) {
        return isFlaggedSpan(spanned, span, Spanned.SPAN_COMPOSING);
    }

    private boolean isFlaggedSpan(@NonNull Spanned spanned, Object span, int flags) {
        return (spanned.getSpanFlags(span) & flags) == flags;
    }

    /**
     * Apply only the spans from src to dst specific by spans.
     *
     * @see {@link android.text.TextUtils#copySpansFrom}
     */
    public static void copySpans(@NonNull Spanned src,
                                 @NonNull Spannable dst,
                                 @NonNull Collection<Object> spans) {
        for (Object span : spans) {
            int start = src.getSpanStart(span);
            int end = src.getSpanEnd(span);
            int flags = src.getSpanFlags(span);
            dst.setSpan(span, start, end, flags);
        }
    }

[0] Actual implementation available here: https://github.com/wikimedia/apps-android-wikipedia/blob/e9ddd8854ff15cde791a2e6fb7754a5450d6f7cf/app/src/main/java/org/wikipedia/richtext/RichTextUtil.java

[1] https://android.googlesource.com/platform/frameworks/base/+/029942f77d05ed3d20256403652b220c83dad6e1/core/java/android/text/InputFilter.java#37

1
  • @S-Sh, I've fixed the rotted implementation link and added the missing copySpans function. Note: your mileage may vary. This code is now old and may or may not be relevant. Sep 24, 2020 at 13:45
0

I would just like to add my solution to the problem(as late as it is). I found that if you add

    yourEditText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);

Then the backspace problems stop

1
  • 1
    Only this helped: editText.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS | InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD); Apr 1, 2016 at 12:46

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.