Expand and give focus to SearchView automatically Expand and give focus to SearchView automatically android android

Expand and give focus to SearchView automatically


You can also call to expandActionView() method in order to force it:

@Overridepublic boolean onCreateOptionsMenu( Menu menu ){    super.onCreateOptionsMenu( menu );    MenuItem searchMenuItem = menu.findItem( R.id.mi_search ); // get my MenuItem with placeholder submenu    searchMenuItem.expandActionView(); // Expand the search menu item in order to show by default the query    return true;}

Search item in the Action Bar layout:

<item        android:id="@+id/mi_search"        android:icon="@drawable/abs__ic_search_api_holo_light"        android:title="@string/search"        android:showAsAction="ifRoom|collapseActionView"        android:actionViewClass="com.actionbarsherlock.widget.SearchView"        />


To make the SearchView expanded by default, call setIconifiedByDefault(false) on it when you initialise it (e.g. in onCreateOptionsMenu(..) or onPrepareOptionsMenu(..)). I've found in most cases this will give it focus automatically, but if not simply call requestFocus() on it too.


If you want to have it iconifiedByDefault, this worked for me. setFocusable and setIconified are needed.

    SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();    searchView.setIconifiedByDefault(true);    searchView.setFocusable(true);    searchView.setIconified(false);    searchView.requestFocusFromTouch();

Update: If you are Using android.support.v7.widget.SearchView the behaviour us very different. clearFocus is needed if you don't want the keyboard pop-up all the time. For some reason the menu is recreated all the time, when using appcompat.

SearchView searchView = (SearchView) menu.findItem(R.id.action_search).getActionView();searchView.setIconified(false);searchView.clearFocus();