How to handle back button of Search View in android

Android_Paradise picture Android_Paradise · Jul 15, 2014 · Viewed 17.5k times · Source

I have Develop an application that have search view in action bar and i got issue when i am do search its filter perfectly but when i am press back button its still showing filter data so my question is what is event of back button of Action Bar Search view.?

enter image description here

My Code of Search View is

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;
    }

};

Filter Method in Adapter

public void filter(String charText) {
    charText = charText.toLowerCase(Locale.getDefault());
    propertyList.clear();

    if (charText.length() == 0) {
       propertyList.addAll(arrayList);
    notifyDataSetChanged();

    } else {
        for (ContactProperty p : arrayList) {
            if (p.getFriendName().toLowerCase(Locale.getDefault())
                    .contains(charText)) {
                propertyList.add(p);
            }
        }
        notifyDataSetChanged();

    }

Answer

Narendra picture Narendra · Sep 15, 2014

You can add listener for this as :

MenuItem searchMenuItem = menu.findItem(R.id.menu_search);
    searchMenuItem.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {

        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            // Do whatever you need
            return true; // KEEP IT TO TRUE OR IT DOESN'T OPEN !!
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            // Do whatever you need
            return true; // OR FALSE IF YOU DIDN'T WANT IT TO CLOSE!
        }
    });