Search code examples
javaandroidsearchandroid-animationsearch-box

Android: implement search in appbar


In my application I have an app bar like the one in the image below

app bar example
(source: jayway.com)

On the left of the appbar I have a TextView and on the right a SearchView and a menu.

How can I implement the search action?

I would like the searchview expanding to the entire width of the app bar and hiding the TextView on the left, when search icon is pressed. Something like Youtube or Gmail apps.

please help me. Thanks.


Solution

  • The item (add it in res/menu/menu.xml):

        <menu>
    <!-- ... ->    
      <item android:id="@+id/action_search"
                  android:title="@string/search_title"
                  android:icon="@drawable/ic_search"
                  android:showAsAction="collapseActionView|ifRoom"
                  android:actionViewClass="android.widget.SearchView" />
        </menu>
    

    don't forget to override

      @Override
        public boolean onCreateOptionsMenu(Menu menu) {
            getMenuInflater().inflate(R.menu.main, menu);
            MenuItem menuItemSearch = menu.findItem(R.id.action_search);
            SearchView searchView = (SearchView) 
            MenuItemCompat.getActionView(menuItemSearch);
            return true;
        }