detecting a click on action bar back button -(OnOptionsItemSelected not calling when click on action bar back button)

Husein Behboodi Rad picture Husein Behboodi Rad · Oct 15, 2014 · Viewed 17.1k times · Source

I have an action bar containing a searchview. When user click on the search button and collapse the search view the action bar shows a back button on the left side.

enter image description here

How can we detect when user click on this back button?

Edit

based on the answer I checked my OnOptionsItemSelected but it is not calling too. This is the code of my OnOptionsItemSelected:

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();

    if (item != null && id == android.R.id.home) {
        if (mNavigationDrawerFragment.isDrawerOpen(Gravity.RIGHT)) {
            mNavigationDrawerFragment.closeDrawer(Gravity.RIGHT);
        } else {
            mNavigationDrawerFragment.openDrawer(Gravity.RIGHT);

        }
        return true;
    }
    if (id == R.id.action_search) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}

Answer

Lisandro Lopez picture Lisandro Lopez · Apr 20, 2015

Put this on onCreateOptionsMenu method:

MenuItemCompat.setOnActionExpandListener(menu.findItem(R.id.action_search), new MenuItemCompat.OnActionExpandListener() {
    @Override
    public boolean onMenuItemActionExpand(MenuItem item) {

        return true;
    }

    @Override
    public boolean onMenuItemActionCollapse(MenuItem item) {

        //DO SOMETHING WHEN THE SEARCHVIEW IS CLOSING

        return true;
    }
});