1

I need to restrict android edittext to allow only alphanumeric characters along with the following characters: space, '.', '_' and '-'.

I have used the following code segmennt for that:

    filters[1] = new InputFilter() {
        public CharSequence filter(CharSequence source, int start,
                                   int end, Spanned dest, int dstart, int dend) {

            if (source instanceof SpannableStringBuilder) {
                SpannableStringBuilder sourceAsSpannableBuilder = (SpannableStringBuilder) source;
                for (int i = end - 1; i >= start; i--) {
                    char currentChar = source.charAt(i);
                    String strCurrentChar = String.valueOf(currentChar);
                    if (!Character.isLetterOrDigit(currentChar)
                            && !".".equals(strCurrentChar)
                            && !"_".equals(strCurrentChar)
                            && !" ".equals(strCurrentChar)) {

                        sourceAsSpannableBuilder.delete(i, i + 1);
                    }
                }
                return source;
            } else {
                StringBuilder filteredStringBuilder = new StringBuilder();
                for (int i = start; i < end; i++) {
                    char currentChar = source.charAt(i);
                    String strCurrentChar = String.valueOf(currentChar);
                    if (Character.isLetterOrDigit(currentChar)
                            || ".".equals(strCurrentChar)
                            || "_".equals(strCurrentChar)
                            || " ".equals(strCurrentChar)) {
                        filteredStringBuilder.append(currentChar);
                    }
                }
                return filteredStringBuilder.toString();
            }

        }
    };

Its working fine restricting all other characters except for the mathematical 'pi' symbol in google-indic keyboard. How can I restrict that also so that the requirement is perfectly fulfilled?

Roohi Zuwairiyah
  • 363
  • 3
  • 15
  • Use this **`android:digits="abcdefghijklmnopqrstuvwxyz1234567890 .-_"`** – AskNilesh Sep 18 '18 at 04:11
  • The above solution doesnt seem to work for me. I tried even removing the filter which i had before,which i have specified in question, and adding this line in layout. but i am able to type all characters. its restricting nothing. Can you make me understand where i am going wrong?? – Roohi Zuwairiyah Sep 18 '18 at 04:49
  • check this https://stackoverflow.com/a/52204322/7666442 – AskNilesh Sep 18 '18 at 04:50
  • ok I got it, It didnt work at first because, i had the below line in my activity.java edittext.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS| InputType.TYPE_TEXT_VARIATION_FILTER); Thankyou Nilesh – Roohi Zuwairiyah Sep 18 '18 at 05:28

0 Answers0