Android SearchView.OnQueryTextListener OnQueryTextSubmit not fired on empty query string

后端 未结 13 892
盖世英雄少女心
盖世英雄少女心 2020-12-05 10:17

I am using Android 4.1.2. I have a SearchView widget on an ActionBar. Documentation on SearchView.OnQueryTextListener

13条回答
  •  谎友^
    谎友^ (楼主)
    2020-12-05 10:36

    It's an old thread but I've found another solution (Kotlin code, but works in Java as well):

    override fun onQueryTextChange(newText: String?): Boolean {
                if(newText == null || newText.isEmpty())
                    searchView.setQuery("\u00A0", false)
                return true
            }
    

    \u00A0 is a character that looks like space, but code-wise it is not. In other words SearchView is not empty. Empty string or " " would not work, because base SearchView uses trim, plus user may want to search text ending or beginning with space. But as far as I know users cannot enter \u00A0 character.

    Then all you need to do is override getQuery to return super.getQuery.replace("\u00A0", "") in your custom SearchView

提交回复
热议问题