Force action Bar show search view

Korniltsev Anatoly picture Korniltsev Anatoly · Jul 13, 2012 · Viewed 16.3k times · Source

I am able to expand search view by action like this

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

But i have a 3-tab activity and i'd like to SearchView be always expanded How may I do that?

Answer

Jonas picture Jonas · Jul 26, 2012

Two steps are necessary.

First, you have to make sure your search menu item is always shown as an action and never moved into the overflow menu. To achieve this set the search menu item's showAsAction attribute to always:

<item
    android:id="@+id/menu_search"
    android:title="Search"
    android:showAsAction="always"
    android:actionViewClass="android.widget.SearchView" />

Second, make sure the action view is not shown in iconified (i.e. collapsed) mode by default. To do this call setIconifiedByDefault(false) on your search view instance:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.my_activity, menu);

    MenuItem searchViewItem = menu.findItem(R.id.menu_search);
    SearchView searchView = (SearchView) searchViewItem.getActionView();
    [...]
    searchView.setIconifiedByDefault(false);

    return true;
}

That should do it.