Reset action bar after using SearchView

戏子无情 提交于 2019-12-06 19:14:27

问题


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:

  1. Search icon appears at the same spot as the edit field (originally it's on the far right).
  2. 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?


回答1:


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.




回答2:


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);
}


来源:https://stackoverflow.com/questions/10419980/reset-action-bar-after-using-searchview

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!