How do I open the SearchView programmatically?

折月煮酒 提交于 2019-11-27 11:04:11

Expand the SearchView with

searchView.setIconified(false);

and collapse it with

searchView.setIconified(true);

You need to change the value of android:showAsAction from ifRoom|collapseActionView to always. The SearchView's attribute android:iconifiedByDefault should be true, which is the default value, otherwise the user can not collapse the SearchView after it was expanded programmatically.

Try to call expandActionView() on MenuItem, not onActionViewExpanded() on ActionView.

It works for me.

MenuItem searchMenuItem = menu.findItem(R.id.menu_search);
searchView = (SearchView) searchMenuItem.getActionView();
searchMenuItem.expandActionView();

If you want to use support library only when necessary, do this

    MenuItem searchMenuItem = menu.findItem(R.id.action_search);
    if (Utils.hasIceCreamSandwich())
        searchMenuItem.expandActionView();
    else MenuItemCompat.expandActionView(searchMenuItem);

else simply do this

    MenuItem searchMenuItem = menu.findItem(R.id.action_search);
    MenuItemCompat.expandActionView(searchMenuItem);

I know this is late but

Try calling expandActionView() to open it and collapseActionView() to close it. You can call requestFocus() on the actual Action View via getActionView() to give the search view focus :)

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