How do I open the SearchView programmatically?

2019-01-10 08:31发布

There is this widget for the ActionBar which called 'SearchView'. When it's not in use, it looks like this:

enter image description here

And when it's in use, it looks like this:

enter image description here

I want (programmatically of course) to open the searchview (make it "in use").

I tried several functions such as:

SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    searchView.setOnQueryTextListener(this);

    searchView.performClick();
    searchView.requestFocus();

But none of those worked...

The SearchView in the XML:

<item android:id="@+id/menu_search"
      android:title="Search"
      android:icon="@drawable/ic_action_search"
      android:showAsAction="ifRoom|collapseActionView"
      android:actionViewClass="android.widget.SearchView" />

4条回答
在下西门庆
2楼-- · 2019-01-10 08:54

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();
查看更多
Emotional °昔
3楼-- · 2019-01-10 09:02

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);
查看更多
Melony?
4楼-- · 2019-01-10 09:15

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.

查看更多
成全新的幸福
5楼-- · 2019-01-10 09:17

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 :)

查看更多
登录 后发表回答