Search code examples
androidnavigation-drawerandroid-support-libraryandroid-toolbar

How to add DrawerLayout to my ToolBar / ActionBar


I have a custom Toolbar that I've set up in my MainActivity to be the top action bar. The question is, how do you implement a NavigationDrawer to display when the ImageView in the toolbar is clicked?

In MainActivity

    @Override
    protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.layout_main_drawer);

    Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(mToolbar);

My layout_main_drawer

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools" android:id="@+id/container"
    android:layout_width="match_parent" android:layout_height="match_parent"
    tools:context="com.XXXX" tools:ignore="MergeRootFrame" />

<android.support.v7.widget.Toolbar
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:minHeight="?attr/actionBarSize"
    android:background="#ccc">
    <ImageView
        android:id="@+id/toolbar_action"
        android:src="@drawable/ic_drawer"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_marginRight="50dp"/>
</android.support.v7.widget.Toolbar>


Solution

  • You can use something like this:

        Toolbar mToolbar = (Toolbar) findViewById(R.id.toolbar);
        setSupportActionBar(mToolbar);
        DrawerLayout mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
        ActionBarDrawerToggle mDrawerToggle = new ActionBarDrawerToggle(
            this,  mDrawerLayout, mToolbar,
            R.string.navigation_drawer_open, R.string.navigation_drawer_close
        );
        mDrawerLayout.setDrawerListener(mDrawerToggle);
    
        mDrawerToggle.syncState();
    

    Pay attention. android.support.v4.app.ActionBarDrawerToggle is deprecated.

    You have to use the android.support.v7.app.ActionBarDrawerToggle. This class has a constructor with the Toolbar.