Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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);
}
like image 603
Husein Behboudi Rad Avatar asked Oct 15 '14 07:10

Husein Behboudi Rad


People also ask

How to add button on action bar?

Add Action Buttons To add actions to the action bar, create a new XML file in your project's res/menu/ directory. The app:showAsAction attribute specifies whether the action should be shown as a button on the app bar.


1 Answers

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;
    }
});
like image 141
Lisandro Lopez Avatar answered Oct 01 '22 19:10

Lisandro Lopez