How to open SearchView programmatically?

Here is this widget for an ActionBar called "SearchView". When not in use, it looks like this:

enter image description here

And when it is used, it looks like this:

enter image description here

I want (programmatically, of course) to open a 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 ...

SearchView in 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" /> 
+74
java android android-actionbar
Jan 09 '13 at 12:54 on
source share
4 answers

Expand 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 attribute android:iconifiedByDefault must be true , which is the default value, otherwise the user cannot collapse the SearchView after programming it programmatically.

+178
Jan 09 '13 at 13:12
source share

Try calling expandActionView() on the MenuItem, rather than onActionViewExpanded () on the ActionView.

This works for me.

 MenuItem searchMenuItem = menu.findItem(R.id.menu_search); searchView = (SearchView) searchMenuItem.getActionView(); searchMenuItem.expandActionView(); 
+54
Sep 21 '13 at 13:03 on
source share

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

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

else just do it

  MenuItem searchMenuItem = menu.findItem(R.id.action_search); MenuItemCompat.expandActionView(searchMenuItem); 
+10
Jun 17 '15 at 22:05
source share

I know it's late, but

Try calling expandActionView () to open it and collapseActionView () to close it. You can call requestFocus () in the actual action view via getActionView () to adjust the search focus :)

+6
Mar 10 '13 at 22:26
source share



All Articles