How do I close a SearchView programmatically?

后端 未结 13 1730
误落风尘
误落风尘 2020-12-23 19:10

I currently have a SearchView in the action bar of my app. When I click the search icon, the SearchView expands and the keyboard pops up as expecte

13条回答
  •  天命终不由人
    2020-12-23 19:28

    To intercept BACK button override onBackPressed() (see docs)

    @Override
    public void onBackPressed() {
    
        if (isSearchViewVisible) {
            SearchView searchView = (SearchView) menu.findItem(R.id.searchBox)
               .getActionView();
    
            // This method does not exist
            searchView.invokeClose();
        } else {
            super.onBackPressed();
        }
    }
    

    EDIT:

    Docs say:

    If necessary, you can expand or collapse the action view in your own code by calling expandActionView() and collapseActionView() on the MenuItem.

提交回复
热议问题