0

I have to restrict users from typing Special Characters in the Search view.

I have already defined the input type as textPersonName, but the users should not be able to type any Special Characters in the first place.

When I tried to cast it to an EditText. It throws an exception, as below:

  val filter: InputFilter = object : InputFilter {
            override fun filter(
                source: CharSequence,
                start: Int,
                end: Int,
                dest: Spanned?,
                dstart: Int,
                dend: Int
            ): CharSequence? {
                for (i in start until end) {
                    if (!Character.isLetterOrDigit(source[i])) {
                        return ""
                    }
                }
                return null
            }
        }
        var etSearch = searchview_filter as EditText
        etSearch.filters = arrayOf(filter)
    

E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.sbi.investtap, PID: 12227
    java.lang.ClassCastException: androidx.appcompat.widget.SearchView cannot be cast to android.widget.EditText
Sweta Jain
  • 3,248
  • 6
  • 30
  • 50
  • https://stackoverflow.com/questions/21828323/how-can-restrict-my-edittext-input-to-some-special-character-like-backslash-t – Abdullah Jubayer Jun 08 '22 at 09:54
  • check this answer. it may help you [link](https://stackoverflow.com/questions/21828323/how-can-restrict-my-edittext-input-to-some-special-character-like-backslash-t) – Abdullah Jubayer Jun 08 '22 at 09:58

2 Answers2

1

This may help you, you need to check your input when users typing data. You need to set your validation inside filter.

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))) {
                return "";
            }
        }
        return null;
    }
};

fetch editText from searchview like this; No need to change edittext's id, because it is default android id of Search EditText.

var etSearch = searchview_filter.findViewById(R.id.search_src_text) as EditText
etSearch.filters = arrayOf(filter)
Bhoomika Patel
  • 1,895
  • 1
  • 13
  • 30
0

This is how you may achieve this in Kotlin:

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))) {
                return "";
            }
        }
        return null;
    }
};


   var etSearch = searchview_filter.findViewById(R.id.search_src_text) as EditText
        etSearch.filters = arrayOf(filter)
Sweta Jain
  • 3,248
  • 6
  • 30
  • 50