How to use SearchView in the toolbar on clicking search icon

Viewed 10639

I am working on the following screen:

1 Screenshot

Screenshot

Here on the toolbar ,i am having a search icon.To add this search icon ,i have used the following code:

menu_friend_list_activity.xml

     <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
        <item
            android:id="@+id/action_search"
            android:icon="@drawable/search"
            android:orderInCategory="100"
            android:title="@string/action_search"
            app:actionViewClass="android.support.v7.widget.SearchView"
            app:showAsAction="always" />
    </menu>

Code inside Activity

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.menu_friend_list_activity, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
                case R.id.action_search:
                Toast.makeText(getApplicationContext(), "Search button clicked", Toast.LENGTH_SHORT).show();
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }

    }

On clicking search icon i want to display the SearchView in toolbar(if i am not wrong here).In short i want to implement the following screen:

Sceenshot

Please tell me how can i implement this.Search will be different for different fragments.

3 Answers

I had similar issue. and I solved as following:

MenuItem searchItem = menu.findItem(R.id.ot_action_search);
final SearchView searchView = (SearchView) searchItem.getActionView();

searchItem.expandActionView();
searchView.setIconified(false);
searchView.setQuery(searchQuery, false);

NB: the expandActionView() should be invoked on searchItem menu item not on the searchView. that was my mistake.

Related