Fragment replacement triggers onQueryTextChange on searchview

前端 未结 7 780
臣服心动
臣服心动 2021-01-07 17:54

This is how I navigate through my app:

  • Open fragment with list
  • Filter list by a text entered in searchview
  • Tap on listitem (list fragment get
7条回答
  •  孤城傲影
    2021-01-07 18:38

    If anyone experiences this same issue, the onQueryTextChange callback will be fired when replacing the Fragment when using the following action in your menu XML file when your SearchView is currently expanded:

    android:showAsAction="always|collapseActionView"
    

    When you attempt to use isVisible() (Java) or isVisible (Kotlin) in the onQueryTextChange callback as a way to determine if the Fragment is actually visible or not, the value returned will always return true.

    The reason for this is that the onQueryTextChange callback will be fired when you're SearchView is currently expanded when you attempt to change Fragment's.

    The default action of collapseActionView at this stage is to collapse the SearchView when changing Fragment's.

    Solution:

    Simply call your SearchView !isIconified (Kotlin) method in your onQueryTextChange callback and only set your logic if it returns false, i.e. the SearchView is currently expanded. Full example described below:

    yourSearchView.setOnQueryTextListener(object: SearchView.OnQueryTextListener {
        override fun onQueryTextSubmit(query: String?): Boolean {
            // Do search query here if you use a submit action
            return true
        }
    
        override fun onQueryTextChange(newText: String?): Boolean {
            if (!yourSearchView.isIconified) {
                // Don't execute your search query here when SearchView is 
                // currently open
                return true
            }
            // Do search query here
            return true
        }
    })
    

提交回复
热议问题