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
I had to implement an OnClickListener for the DrawerToggle:
mDrawerToggle.setToolbarNavigationClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
popStackIfNeeded();
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
mActionBar.setDisplayHomeAsUpEnabled(false);
mDrawerToggle.setDrawerIndicatorEnabled(true);
}
});
this fixed my issue.
I had several issues using the setSupportActionBar() method. It also ignores certain color themes, so you can't style the back arrow or overflow icon (don't remember which). I just did away with ActionBar integration and use the Toolbar natively. So, as an alternative, you could do that as follows.
Just include the toolbar like you would normally, in your layout, assume it's using an id of @+id/toolbar.
Then, in code:
_toolbar = (Toolbar) findViewById(R.id.toolbar);
_toolbar.setNavigationOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
handleNavButtonPress();
}
});
_toolbar.setOnMenuItemClickListener(_menuItemClickListener);
_toolbar.inflateMenu(R.menu.message_list_menu);
Menu menu = _toolbar.getMenu();
In this case, _menuItemClickListener can almost literally be your current onOptionsItemSelected() method renamed. You just don't have to check for menu being null anymore.
To remove items from the menu, just call menu->clear(). So in my onPause
, I clear the menus and onResume, I inflate them, in my fragments, and each fragment sets the click handler in onResume. You need to always clean up, because Android won't do that for you in this approach, and the toolbar will keep adding menus every time you inflate.
One last note, to make it all work, you have to disable the action bar completely and remove it from the style.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With