Search code examples
androidandroid-edittextandroid-input-filter

Restrict special characters & space programmatically


I want to restrict user from entering special characters & space programmatically. Below is my code

InputFilter[] alphaNumericFilter = new InputFilter[2];
        alphaNumericFilter[0] = new InputFilter() {
            @Override
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
                for (int k = start; k < end; k++) {
                    boolean isLetterOrDigit = Character.isLetterOrDigit(source.charAt(k));
                    boolean isSpaceChar = Character.isSpaceChar(source.charAt(k));
                    if ((source.length() > 0 && isSpaceChar) ||
                            (!isLetterOrDigit && !isSpaceChar) ||
                            (isSpaceChar && TextUtils.isEmpty(dest))) {
                        return "";
                    }
                }
                return null;
            }
        };

on pressing space it deleting last character.


Solution

  • Finally I have resolved this issue by adding below line in the code

    mEditText.setInputType(InputType.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD);
    

    This line will not show suggestions on keyboard.