1

How can I handle the click event on the back arrow in the searchview widget:

enter image description here

I tried this code but it doesn't work:

searchtollbar.setNavigationOnClickListener(new View.OnClickListener() {
    @Override
    public void onClick(View v) {
        Log.d(TAG, "back arrow clicked");
    }

});

also I tried this one:

MenuItemCompat.setOnActionExpandListener(item_search, new 
MenuItemCompat.OnActionExpandListener() {
    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {
        // Do something when collapsed
        return true;
    }

    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {
        // Do something when expanded
        return true;
    }
});

The problem with the above code is that calling onMenuItemActionCollapse() method also executes onQueryTextChange() which is undesirable.

So some help please.

Toni Joe
  • 7,715
  • 12
  • 50
  • 69
  • This is not a duplicate. This issue describes a particular problem where the back button navigation doesn't work correctly due to the presence of a SearchView. It is not a general 'how to add back button to toolbar' question. – Tim Malseed Jul 18 '19 at 14:19

2 Answers2

1

To handle that you have to override onOptionsItemSelected method.

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle item selection
        switch (item.getItemId()) {
            case android.R.id.home:
                // handle back event.
                return true;

            default:
                return super.onOptionsItemSelected(item);
        }
    }
Drumil Jani
  • 111
  • 5
0

Try with

MenuItem item = menu.findItem(R.id.action_search);

    SearchView searchView = new SearchView(((MainActivity) mContext).getSupportActionBar().getThemedContext());
    item.setOnActionExpandListener(new MenuItem.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionExpand(MenuItem menuItem) {
            Log.d( TAG, "expand" );
            return true;
        }

        @Override
        public boolean onMenuItemActionCollapse(MenuItem menuItem) {
            Log.d( TAG, "collapse" );
           

            return true;
        }
    });