how to handle back button of Search View in android

deepika taywade picture deepika taywade · Sep 15, 2014 · Viewed 11.9k times · Source
SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(Menus.SEARCH));
searchView.setQueryHint(this.getString(R.string.search));
editSearch = (EditText) searchView.findViewById(android.support.v7.appcompat.R.id.search_src_text);
editSearch.setHintTextColor(getResources().getColor(R.color.white));
searchView.setOnQueryTextListener(OnQuerySearchView);


private OnQueryTextListener OnQuerySearchView = new OnQueryTextListener() {

    @Override
    public boolean onQueryTextSubmit(String newText) {
        if (TextUtils.isEmpty(newText)) {
            listAllContact.clearTextFilter();
        } else {
            listAllContact.setFilterText(newText.toString());
        }
        return true;
    }

    @Override
    public boolean onQueryTextChange(String newText) {
        String text = editSearch.getText().toString()
                .toLowerCase(Locale.getDefault());
        adapter.filter(text);
        return true;
    }

};

Answer

Atetc picture Atetc · Apr 21, 2015

If you use android.support.v7.widget.SearchView as menu item:

<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:title=""
        app:showAsAction="ifRoom|collapseActionView"
        app:actionViewClass="android.support.v7.widget.SearchView"/>
</menu>

You can handle back button (for expanded state) with:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu, menu);
    MenuItem searchItem = menu.findItem(R.id.action_search);
    searchItem.expandActionView();
    MenuItemCompat.setOnActionExpandListener(searchItem, new MenuItemCompat.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            // Write your code here
            return true;
        }
    });
}