Home » Android » android – Show SearchWidget in ActionBar if user presses the device's search button

android – Show SearchWidget in ActionBar if user presses the device's search button

Posted by: admin June 15, 2020 Leave a comment


I set up a SearchWidget as described in the Android API Guide. It properly displays a magnifying glass icon in the Action Bar and if I click on it, it launches the search widget within the Action Bar (an input field with dark background).

However, if I press the virtual device’s search button, then a different search field is launched: It has a white background and does not invoke the callback methods I specified.

So I added this to my MainActivity class:

public boolean onSearchRequested() {
    SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
    return false;

The set up of the search widget is exactly the same as it is described in the docs:

SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setOnQueryTextListener(new CustomSearchQueryTextListener());

My searchable.xml:

<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"

And AndroidManifest.xml:

        android:uiOptions="splitActionBarWhenNarrow" >
            <action android:name="android.intent.action.MAIN" />
            <category android:name="android.intent.category.LAUNCHER" />
            <action android:name="android.intent.action.SEARCH" />
        <meta-data android:name="android.app.searchable" android:resource="@xml/searchable"/>

The reason why I tried the setIconfied() method is that in the Android API Guide it says under “The ability to toggle the search box visibility”:

“By default, the search widget is “iconified,” meaning that it is
represented only by a search icon (a magnifying glass), and expands to
show the search box when the user touches it. As shown above, you can
show the search box by default, by calling
setIconifiedByDefault(false). You can also toggle the search widget
appearance by calling setIconified().”

I also tried to call startSearch("", false, null, false); but this brings up the same search field with the white background.

So my question is: Is it possible to launch the search widget within the action bar if the user presses the device’s search button, i.e. peform exactly the same action as if the search menu item is clicked?

How to&Answers:

While writing this question I came up with the solution by myself. I still decided to post it along with the answer, because it does not seem like this question has been asked on SO before and maybe someone encounters the same problem and/or comes up with a better solution.

All you need to do is call expandActionView() on the search menu item, and everything works like expected:

public boolean onSearchRequested() {
    return true;