asmgx asmgx - 11 months ago 98
Android Question

How do I capture SearchView's clear button click?

How can I capture the event of user click on clear

text by clicking on the X button on the right

I already captured
event but, this is for any text change not for that X button

Answer Source

After trying a lot of combinations, I found how to capture the event behind the X button in SearchView

Below is a code snippet from onCreateOptionsMenu function in one of my apps. mSearchMenu and mSearchView are global variables. The X is actually an ImageView with ID search_close_btn and the text area is an EditText view with ID search_src_text

    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu items for use in the action bar
        MenuInflater inflater = getMenuInflater();
        inflater.inflate(, menu);
        mSearchMenu = menu.findItem(;

            // Get the SearchView and set the searchable configuration
            SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
            mSearchView = (SearchView) menu.findItem(;

            // Assumes current activity is the searchable activity
            mSearchView.setIconifiedByDefault(false); // Do not iconify the widget; expand it by default

            // Get the search close button image view
            ImageView closeButton = (ImageView)mSearchView.findViewById(;

            // Set on click listener
            closeButton.setOnClickListener(new View.OnClickListener() {

                public void onClick(View v) {
                    LoggerUtils.d(LOG, "Search close button clicked");
                    //Find EditText view
                    EditText et = (EditText) findViewById(;

                    //Clear the text from EditText view

                    //Clear query
                    mSearchView.setQuery("", false);
                    //Collapse the action view
                    //Collapse the search widget

        // When using the support library, the setOnActionExpandListener() method is
        // static and accepts the MenuItem object as an argument
        mSearchMenu.setOnActionExpandListener(new OnActionExpandListener() {

            public boolean onMenuItemActionExpand(MenuItem item) {
                //Nothing to do here
                LoggerUtils.d(LOG, "Search widget expand ");
                return true; // Return true to expand action view

            public boolean onMenuItemActionCollapse(MenuItem item) {
                LoggerUtils.d(LOG, "Search widget colapsed ");
                return true; // Return true to collapse action view

        return super.onCreateOptionsMenu(menu);