How do I close a SearchView programmatically?
Based on @MarcinOrlowski answer, also you can use:
@Override
public void onBackPressed() {
if (!searchView.isIconified()) {
searchView.setIconified(true);
} else {
super.onBackPressed();
}
}
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();
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()