22

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?

TZHX
  • 5,291
  • 15
  • 47
  • 56
Korniltsev Anatoly
  • 3,676
  • 2
  • 26
  • 37

1 Answers1

62

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.

Jonas
  • 2,126
  • 21
  • 16
  • 1
    getting NPE at thsi line searchView.setIconifiedByDefault i have used this code SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView(); searchView.setIconifiedByDefault(false); – Erum Sep 02 '15 at 07:34
  • Try get SearchView by MenuItemCompat.getActionView(menu.findItem(R.id.menu_search)) if you are using AppCompat SearchView – Roman_D Sep 16 '16 at 15:09