Fragment replacement triggers onQueryTextChange on searchview

前端 未结 7 839
臣服心动
臣服心动 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:31

    The problem is ActionBar (and subcomponents) are collapsed when the fragment holding it is replaced. When this happens the SearchView query is cleared as seen in onActionViewCollapsed. Workarounds include:

    Prevent collapsing

    Remove setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW); from the searchview's creation code or android:showAsAction="collapseActionView" from its xml code.

    This will affect how/when the view's close/voicesearch buttons are displayed upon attempting to collapse it

    It would also be possible to prevent collapsing by overriding SearchView's onActionViewCollapsed() method to do nothing but would accomplish the same.

    Ignore query changes when appropriate

    When the fragment is not valid (being replaced) then ignore query changes that would otherwise cause the fragment to alter its saved query text or layout (changing the layout would cause an exception if the fragment doesn't actually have view content).

    public boolean onQueryTextChange(String newText) {
        if (!isVisible()) {
            // The fragment was replaced so ignore
            return true;
        }
        // Text was actually changed, perform search
        return true;
    }
    

    This would be the better option as it doesn't affect the functionality of the searchview.

提交回复
热议问题