AppCompat v7 Toolbar onOptionsItemSelected not called

Informatic0re picture Informatic0re · Oct 27, 2014 · Viewed 21k times · Source

I changed from the original ActionBar to the AppCompat Toolbar and setSupportActionBar(toolbar). When I am using getSupportActionBar() and setDisplayHomeAsUpEnabled(true) for the back arrow, the click never calls onOptionsItemSelected or any other listener method.

Do I have to implement some special listener for it? Befor everything was working just fine.

EDIT: Initialise the ActionBar:

mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
mActionBar = getSupportActionBar();
mActionBar.setHomeButtonEnabled(true);

and after replacing the content with a Fragment I do this:

mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
mDrawerToggle.setDrawerIndicatorEnabled(false);
mActionBar.setDisplayHomeAsUpEnabled(true);

Answer

Andrei Lupsa picture Andrei Lupsa · Jan 27, 2015

I know this question has been answered but I found the real cause of the problem after 2 days of frustration.

Take a look at the ActionBarDrawerToggle documentation: https://developer.android.com/reference/android/support/v7/app/ActionBarDrawerToggle.html

Notice the two constructors there. My mistake was that I was using the second constructor that was taking a toolbar as a parameter. It took me so long to notice the last line in the consturctor documentation: "Please use ActionBarDrawerToggle(Activity, DrawerLayout, int, int) if you are setting the Toolbar as the ActionBar of your activity."

After using the first constructor onOptionsItemSelected() was called with no issues.

Don't forget to call the ActionBarDrawerToggle.onConfigurationChanged() and onOptionsItemSelected() from your activity as described in the last part here: http://developer.android.com/training/implementing-navigation/nav-drawer.html