Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Toggle the Navigation Drawer via the Action Bar title

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!

like image 758
David Crozier Avatar asked Sep 06 '13 15:09

David Crozier


1 Answers

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);
}
like image 152
nsL Avatar answered Dec 10 '22 08:12

nsL