Toggle the Navigation Drawer via the Action Bar title

David Crozier picture David Crozier · Sep 6, 2013 · Viewed 19.4k times · Source

I'm trying to allow the user to open/close the navigation drawer in my app by tapping the action bar title (this is how the current Android Gmail app is set up). At the moment, the user can toggle the drawer by tapping the app/drawer icon or by sliding it in with a left-right swipe. However, the action bar title itself is not clickable. According to the developer docs, clicking the action bar title should "dispatch onOptionsItemSelected to the host Activity with a MenuItem with item ID android.R.id.home" when we use NAVIGATION_MODE_STANDARD but for some reason I can't get the title to behave this way.

I believe the Navigation Drawer itself is fine, but here is how I set up the Action Bar:

private void configureActionBar(CharSequence mTitle) {

    ActionBar actionBar = getActionBar();

    actionBar.setDisplayHomeAsUpEnabled(true);
    actionBar.setHomeButtonEnabled(true);

    actionBar.setIcon(R.drawable.ic_blank);

    GradientDrawable gd = new GradientDrawable(GradientDrawable.Orientation.TOP_BOTTOM,
                new int[] {
                0xFF004700, 0xFF002900
                });

    gd.setCornerRadius(0f);

    actionBar.setBackgroundDrawable(gd);

    // set the title of the action bar using the given title
    actionBar.setTitle(mTitle);

}

Any suggestions would be greatly appreciated!

Answer

nsL picture nsL · Sep 6, 2013

If you want the drawer to open by tapping Icon/Title of ActionBar, i suggest you to use the ActionBarDrawerToggle class provided in the support library(android.support.v4.app.ActionBarDrawerToggle)

Reference: https://developer.android.com/reference/android/support/v4/app/ActionBarDrawerToggle.html

Example of use:
https://developer.android.com/training/implementing-navigation/nav-drawer.html

The trick comes when capturing the event in onOptionsItemSelected(), that you have to pass it to the ActionBarDrawerToggle, so it can handle the open/close drawer request:

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Pass the event to ActionBarDrawerToggle, if it returns
    // true, then it has handled the app icon touch event
    if (mDrawerToggle.onOptionsItemSelected(item)) {
      return true;
    }
    // Handle your other action bar items...

    return super.onOptionsItemSelected(item);
}