How to filter the input of EditText?

twlkyao picture twlkyao · May 15, 2015 · Viewed 19.8k times · Source

I want to filter the input of an EditText, only digits and letters are allowed, first I use TextWatcher to deal with the last input character, but when you move the cursor or you past some content to the EditText, this method failed, now I want to know is there a way to filter the illegal input and give the user a feedback.

Answer

Don Chakkappan picture Don Chakkappan · May 15, 2015

Add InputFilter to your EditText & provide a Toast for user . This code snippet will help you.

 InputFilter filter = new InputFilter() {
                public CharSequence filter(CharSequence source, int start, int end,
                        Spanned dest, int dstart, int dend) {
                    for (int i = start; i < end; i++) {
                        if (!Character.isLetterOrDigit(source.charAt(i))) { // Accept only letter & digits ; otherwise just return
                            Toast.makeText(context,"Invalid Input",Toast.LENGTH_SHORT).show();
                            return "";
                        }
                    }
                    return null;
                }

            };

        editText.setFilters(new InputFilter[] { filter });