Search code examples
androidandroid-actionbarandroid-actionbar-compatandroid-actionbaractivity

How do I listen for click events for an ActionBar nav button when a SearchView is visible?


I'm trying to catch click events for the nav button in my ActionBar. This method catches most clicks:

@Override
public boolean onOptionsItemSelected(MenuItem menuItem) {
    if (menuItem.getItemId() == android.R.id.home) {
        // Nav button pressed. Do stuff here.
        return true;
    }

    return super.onOptionsItemSelected(menuItem);
}

However it isn't called when my SearchView is visible. In this state, tapping the button closes the SearchView. Tapping it again triggers the callback above.

This isn't good enough for me. My activity (which extends from ActionBarActivity) is dedicated to search, so closing the SearchView doesn't make sense. I just want to navigate the user out of there on the first click. (Please no comments about UX or "why" I want to change the default behavior. I have a spec to follow!)

Thanks in advance...


Solution

  • To know when the user closed the SearchView you can check when the menu item is collapsed:

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
    
        MenuItemCompat.setOnActionExpandListener(menu.findItem(R.id.search_view), new MenuItemCompat.OnActionExpandListener() {
            @Override
            public boolean onMenuItemActionExpand(MenuItem item) {
                //The SearchView is opening
                return true;
            }
    
            @Override
            public boolean onMenuItemActionCollapse(MenuItem item) {
                //The SearchView is closing. Do stuff here.
                return true;
            }
        });
    
        return true;
    }