Android – Material Design SearchView example

This is step-by-step instruction how to implement Material Design SearchView for pre-lollipop devices:

Step 1: Add SearchView menu item to res/menu/menu_main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android"
   xmlns:app="http://schemas.android.com/apk/res-auto"
   xmlns:tools="http://schemas.android.com/tools" tools:context=".MainActivity">
    <item
       android:id="@+id/action_search"
       android:title="@android:string/search_go"
       android:icon="@drawable/icon_toolbar_search"
       app:showAsAction="always|collapseActionView"
       app:actionViewClass="android.support.v7.widget.SearchView"
       android:visible="false"/>
    <item android:id="@+id/action_settings" android:title="@string/action_settings"
       android:orderInCategory="100" app:showAsAction="never" />
</menu>

Note that, now menu item is INVISIBLE. To make it visible change android:visible to “true”. Why here I am setting it false. In my app, it should be invisible at first.

Moreover, this menu item uses following drawable. Download it and paste into res/drawable
icon_toolbar_search

Step2: Create OnQueryTextListener. This listener will serve as trigger for entered text to SearchView(this code should be in your Activity)

    SearchView.OnQueryTextListener listener = new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextSubmit(String query) {
            return false;
        }

        @Override
        public boolean onQueryTextChange(String newText) {
            // newText is text entered by user to SearchView
            Toast.makeText(getApplicationContext(), newText, Toast.LENGTH_LONG).show();
            return false;
        }
    };

Step 3: Let’s initiate our menu item and connect SearchView to our menu item:

    private SearchView mSearchView;
    private MenuItem searchMenuItem;

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        searchMenuItem = menu.findItem(R.id.action_search);
        mSearchView = (SearchView) searchMenuItem.getActionView();
        mSearchView.setOnQueryTextListener(listener);
        return true;
    }

Note that getActionView() method requires minSdkVersion 11. You can set it on grade.build file.

Step 4: This step is optional. I am using this SearchView while I am using fragments inside Activity. I want to show SearchView and its menu item when I open specific fragment. Fragment is opened when I select first menu item from navigation drawer.

searchMenuItem.setVisible(position == 0);

Result:
Screenshot_2015-08-12-13-38-08