-1

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.

Community
  • 1
  • 1
Jay
  • 145
  • 2
  • 12

1 Answers1

1

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;
    }
Martin Pfeffer
  • 12,471
  • 9
  • 59
  • 68
  • Sorry where I have to add this? – Jay Jun 16 '16 at 14:52
  • thx, it works. But if I would use android.support.v7.widget.SearchView instead of android.widget.SearchView how can I implement the java onCreateOptionsMenu() ? Because this code not worws for android.support.v7.widget.SearchView ... – Jay Jun 16 '16 at 21:20
  • Did you link the support v7 in gradle? – Martin Pfeffer Jun 16 '16 at 22:12