SearchView.OnCloseListener does not get invoked

To get notified when the 'x' icon is clicked, I added an on click listener to the SearchView 'x' button.

Find the SearchView 'x' button by id and attach the OnClickListener:

mSearchView.findViewById(R.id.search_close_btn)
    .setOnClickListener(this);

The view search_close_btn is present in the SearchView layout provided by the Android framework.


I ran into same problem on android 4.1.1. Looks like it is a known bug: https://code.google.com/p/android/issues/detail?id=25758

Anyway, as a workaround i used state change listener (when SearchView is detached from action bar, it is also closed obviously).

view.addOnAttachStateChangeListener(new OnAttachStateChangeListener() {

    @Override
    public void onViewDetachedFromWindow(View arg0) {
        // search was detached/closed
    }

    @Override
    public void onViewAttachedToWindow(View arg0) {
        // search was opened
    }
});

Above code worked well in my case.


In order call onClose() method from SearchView.OnCloseListener. I made it working in the following way. Add this to your searchview

searchView.setIconifiedByDefault(true);
searchView.setOnCloseListener(this);

Now implement this onclick listener

  searchView.findViewById(R.id.search_close_btn)
                .setOnClickListener(new View.OnClickListener() {
                    @Override
                public void onClick(View v) {
                    Log.d("called","this is called.");
                    searchView.setQuery("",false);
                    searchView.setIconified(true);

                }
            });

This worked for me. Sharing so that it can help somebody else also. Thanks