How do I close a SearchView programmatically?
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 expected. Clicking the "X" in the SearchView
box closes the SearchView
as expected. However, when the SearchView
is activated and I press the "back" button, my app is exited. This is the correct behavior, but what I am trying to do now is to capture back button press and just have it close the SearchView
(not my app) when the SearchView
is visible. Is there a way to invoke the SearchView
OnCloseListener()
programmatically on a back button press? For example, something like this:
// On a back button press, if we are currently searching,
// close the SearchView. Otherwise, invoke normal back button
// behavior.
public boolean onKeyDown(int keyCode, KeyEvent event) {
if (keyCode == KeyEvent.KEYCODE_BACK) {
if (isSearchViewVisible) {
SearchView searchView = (SearchView) menu.findItem(R.id.searchBox)
.getActionView();
// This method does not exist
searchView.invokeClose();
return true;
}
}
return super.onKeyDown(keyCode, event);
}
Based on @MarcinOrlowski answer, also you can use:
@Override
public void onBackPressed() {
if (!searchView.isIconified()) {
searchView.setIconified(true);
} else {
super.onBackPressed();
}
}
Use
searchView.setIconified(true)
I also used MenuItemCompat.collapseActionView
MenuItemCompat.collapseActionView(menuItem)
EDITED
This method was deprecated in API level 26.1.0. Use collapseActionView() directly.
MenuItem#collapseActionView()
There is a simple way to do this:
@Override
public void onBackPressed() {
if (!searchView.isIconified()) {
searchView.onActionViewCollapsed();
} else {
super.onBackPressed();
}
}
or use:
myToolBar.collapseActionView();
This will make the searchView to collapse before you press the back then the back action will be called.
Both solutions will work.
this is the only thing that does it for me:
toolbar.collapseActionView();
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.