I'm using SearchView
widget to enable searching in my app. After the initial click on the search icon, the SearchView
widget expands into the search field and the "back" arrow is shown next to the application icon. If I click the application icon the action bar reverts to the initial state (no "back" arrow) and the SearchView
reverts back to icon.
Now the problem: after the search is executed the action bar doesn't change, the only way to revert is to click the application icon or phone's "back" arrow. Not good since I want the action bar go to the initial state when the search is done. I tried SearchView.setIconofied(true)
but there are 2 problems:
- Search icon appears at the same spot as the edit field (originally it's on the far right).
- Action bar still displays "back" arrow.
I think the problem I'm facing results from deviating from the regular navigation pattern. In my case everything is happening inside the same activity (search results are displayed in the same activity that hosts the action bar), so for example executing Activity.finish()
simply makes app exit.
How do I trigger "go back one step" of the action bar? Or simulate click on the application icon?
It sounds like you've set this up as a collapsible action view on a MenuItem. You can call collapseActionView() on that MenuItem instance to send it back to its closed state.
the method collapseActionView() only works from API level 14. If you're looking to support for earlier versions of android, then you should use MenuItemCompat library.
Here's my solution to collapse the searchview and reset the action bar...
private MenuItem searchMenuItem; @Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.main_menu, menu); SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE); searchMenuItem = menu.findItem(R.id.action_search); final SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchMenuItem); searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName())); searchView.setIconifiedByDefault(false); customizeSearchView(searchView); return super.onCreateOptionsMenu(menu); } @Override protected void onNewIntent(Intent intent) { setIntent(intent); if (searchMenuItem != null) { if (MenuItemCompat.expandActionView(searchMenuItem)) { MenuItemCompat.collapseActionView(searchMenuItem); } else if (MenuItemCompat.collapseActionView(searchMenuItem)) { MenuItemCompat.expandActionView(searchMenuItem); } } handleIntent(intent); }