Search code examples
androidandroid-toolbarhamburger-menu

Showing hamburger icon on a custom toolbar?


I made a NavigationView and included getSupportActionBar().setDisplayHomeAsUpEnabled(true);in my code to show the hamburger button, and it worked. but then i removed the default toolbar (by setting AppTheme in styles values to parent="Theme.AppCompat.Light.NoActionBar"), and implemented my own toolbar in the layout. And now instead of the Hamburger button, it shows the back button, although clicking on it draws the NavigationView. What should i do?

My Java code:

private DrawerLayout sideBar;
private ActionBarDrawerToggle sideBarToggle;
private Toolbar actionToolbar;

@Override
public void onCreate(...) {

    sideBar = (DrawerLayout) findViewById(R.id.sqliteLayout);
    sideBarToggle = new ActionBarDrawerToggle(this, sideBar, actionToolbar, R.string.sideBarOpen, R.string.sideBarClose);
    actionToolbar = (Toolbar) findViewById(R.id.navAction);
    sideBar.addDrawerListener(sideBarToggle);
    sideBarToggle.syncState();
    setSupportActionBar(actionToolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);
}

@Override
public boolean onOptionsItemSelected(MenuItem item) {

    if(sideBarToggle.onOptionsItemSelected(item)){
        return true;}

    return super.onOptionsItemSelected(item);
}

My Toolbar code:

    <android.support.v7.widget.Toolbar 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:orientation="vertical"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/navAction"
        android:background="@color/colorPrimary"
        app:theme="@style/Base.Theme.AppCompat.Light.DarkActionBar">

    </android.support.v7.widget.Toolbar>

SOLUTION:

I reordered the java code to this, and removed the 3rd argument in new ActionBarDrawerToggle(...) and it worked!

    actionToolbar = (Toolbar) findViewById(R.id.navAction);
    setSupportActionBar(actionToolbar);
    sideBar = (DrawerLayout) findViewById(R.id.sqliteLayout);
    sideBarToggle = new ActionBarDrawerToggle(this, sideBar,  R.string.sideBarOpen, R.string.sideBarClose);
    sideBar.addDrawerListener(sideBarToggle);
    sideBarToggle.syncState();
    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

Solution

  • Call setSupportActionBar(actionToolbar); before you set up your ActionBarDrawerToggle.

    ActionBarDrawerToggle uses getSupportActionBar() under the hood, so all the work it is doing is wiped out when you call setSupportActionBar afterwards.