Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I open the SearchView programmatically?

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" /> 
like image 807
Eli Revah Avatar asked Jan 09 '13 12:01

Eli Revah


People also ask

How to open search View programmatically in Android?

getActionView(); searchView. setOnQueryTextListener(this); searchView. performClick(); searchView. requestFocus();

How to use a SearchView in Android?

SearchView widget can be implemented over ToolBar/ActionBar or inside a layout. SearchView is by default collapsible and set to be iconified using setIconifiedByDefault(true) method of SearchView class. For making search field visible, SearchView uses setIconifiedByDefault(false) method.

How to Implement SearchView in ToolBar in Android?

Add the Search View to the App Bar To add a SearchView widget to the app bar, create a file named res/menu/options_menu. xml in your project and add the following code to the file. This code defines how to create the search item, such as the icon to use and the title of the item.


2 Answers

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.

like image 199
Matthias Robbers Avatar answered Sep 19 '22 08:09

Matthias Robbers


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(); 
like image 24
qbait Avatar answered Sep 20 '22 08:09

qbait