With the release of Android 5.0 Lollipop, the new material design style navigation drawer spans the full height of the screen and is displayed over the ActionBar and overlaps the translucent StatusBar. Read the material design style navigation drawer document for specs on styling your navigation drawer.

Usage

This guide explains how to setup a basic material design style drawer filled with navigation items that switch different fragments into the content area. In this way, you can define multiple fragments, and then define the list of options which will display in the drawers items list. Each item when clicked will switch the relevant fragment into the activity's container view.

Setup

Make sure to setup the Google Design Support Library before using Google's new NavigationView, announced as part of the Android M release. The NavigationView should be backwards compatible with all versions down to Android 2.1.

Make sure you have this Gradle dependency added to your app/build.gradle file:

dependencies{implementation'com.android.support:design:27.1.1'}

Download Nav Drawer Item icons

Download the following icons and add them to your drawable folders by copying and pasting them into the drawable folder or using the New Image Asset dialog to create versions for each density.

Define Fragments

Next, you need to define your fragments that will be displayed within the activity. These can be any support fragments you define within your application. Make sure that all the fragments extend from android.support.v4.app.Fragment.

Setup Toolbar

In order to slide our navigation drawer over the ActionBar, we need to use the new Toolbar widget as defined in the AppCompat v21 library. The Toolbar can be embedded into your view hierarchy which makes sure that the drawer slides over the ActionBar.

Create a new layout file res/layout/toolbar.xml with the following code:

Note that when the android:fitsSystemWindows attribute is set to true for a view, the view would be laid out as if the StatusBar and the ActionBar were present i.e. the UI on top gets padding enough to not be obscured by the navigation bar. Without this attribute, there is not enough padding factored into consideration for the ToolBar:

We want our main content view to have the navigation bar and hence android:fitsSystemWindows is set to true for the Toolbar.

To use the Toolbar as an ActionBar, you need to disable the default ActionBar. This can be done by setting the app theme in styles.xml file.

Also note that normally you should decide on your color scheme by going to Material Palette and choosing a primary and dark primary color. For this example, we will pick purple-based colors as shown in the screenshot.

Note: If you forget to disable the ActionBar in styles.xml, you are likely to see a java.lang.IllegalStateException with an error message that reads This Activity already has an action bar supplied by the window decor. Do not request Window.FEATURE_ACTION_BAR and set windowActionBar to false in your theme to use a Toolbar instead. If you see this message, you need to make sure to follow the previous steps.

<!-- This DrawerLayout has two children at the root --><android.support.v4.widget.DrawerLayoutxmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"android:id="@+id/drawer_layout"android:layout_width="match_parent"android:layout_height="match_parent"><!-- This LinearLayout represents the contents of the screen --><LinearLayoutandroid:layout_width="match_parent"android:layout_height="match_parent"android:orientation="vertical"><!-- The ActionBar displayed at the top --><includelayout="@layout/toolbar"android:layout_width="match_parent"android:layout_height="wrap_content"/><!-- The main content view where fragments are loaded --><FrameLayoutandroid:id="@+id/flContent"app:layout_behavior="@string/appbar_scrolling_view_behavior"android:layout_width="match_parent"android:layout_height="match_parent"/></LinearLayout><!-- The navigation drawer that comes from the left --><!-- Note that `android:layout_gravity` needs to be set to 'start' --><android.support.design.widget.NavigationViewandroid:id="@+id/nvView"android:layout_width="wrap_content"android:layout_height="match_parent"android:layout_gravity="start"android:background="@android:color/white"app:menu="@menu/drawer_view"/></android.support.v4.widget.DrawerLayout>

Now, let's setup the drawer in our activity. We can also setup the menu icon too.

publicclassMainActivityextendsAppCompatActivity{privateDrawerLayoutmDrawer;privateToolbartoolbar;privateNavigationViewnvDrawer;// Make sure to be using android.support.v7.app.ActionBarDrawerToggle version.
// The android.support.v4.app.ActionBarDrawerToggle has been deprecated.
privateActionBarDrawerToggledrawerToggle;@OverrideprotectedvoidonCreate(BundlesavedInstanceState){super.onCreate(savedInstanceState);setContentView(R.layout.activity_main);// Set a Toolbar to replace the ActionBar.
toolbar=(Toolbar)findViewById(R.id.toolbar);setSupportActionBar(toolbar);// Find our drawer view
mDrawer=(DrawerLayout)findViewById(R.id.drawer_layout);}@OverridepublicbooleanonOptionsItemSelected(MenuItemitem){// The action bar home/up action should open or close the drawer.
switch(item.getItemId()){caseandroid.R.id.home:mDrawer.openDrawer(GravityCompat.START);returntrue;}returnsuper.onOptionsItemSelected(item);}}

Navigating between Menu Items

Setup a handler to respond to click events on the navigation elements and swap out the fragment. This can be put into the activity directly:

publicclassMainActivityextendsAppCompatActivity{// ...
@OverrideprotectedvoidonCreate(BundlesavedInstanceState){// ...From section above...
// Find our drawer view
nvDrawer=(NavigationView)findViewById(R.id.nvView);// Setup drawer view
setupDrawerContent(nvDrawer);}privatevoidsetupDrawerContent(NavigationViewnavigationView){navigationView.setNavigationItemSelectedListener(newNavigationView.OnNavigationItemSelectedListener(){@OverridepublicbooleanonNavigationItemSelected(MenuItemmenuItem){selectDrawerItem(menuItem);returntrue;}});}publicvoidselectDrawerItem(MenuItemmenuItem){// Create a new fragment and specify the fragment to show based on nav item clicked
Fragmentfragment=null;ClassfragmentClass;switch(menuItem.getItemId()){caseR.id.nav_first_fragment:fragmentClass=FirstFragment.class;break;caseR.id.nav_second_fragment:fragmentClass=SecondFragment.class;break;caseR.id.nav_third_fragment:fragmentClass=ThirdFragment.class;break;default:fragmentClass=FirstFragment.class;}try{fragment=(Fragment)fragmentClass.newInstance();}catch(Exceptione){e.printStackTrace();}// Insert the fragment by replacing any existing fragment
FragmentManagerfragmentManager=getSupportFragmentManager();fragmentManager.beginTransaction().replace(R.id.flContent,fragment).commit();// Highlight the selected item has been done by NavigationView
menuItem.setChecked(true);// Set action bar title
setTitle(menuItem.getTitle());// Close the navigation drawer
mDrawer.closeDrawers();}// ...
}

Add Navigation Header

The NavigationView also accepts a custom attribute that can reference a layout that provides a header of our layout. For instance, you can create a layout/nav_header.xml similar to the following:

This app:headerLayout inflates the specified layout into the header automatically. This can alternatively be done at runtime with:

// Lookup navigation view
NavigationViewnavigationView=(NavigationView)findViewById(R.id.nav_draw);// Inflate the header view at runtime
ViewheaderLayout=navigationView.inflateHeaderView(R.layout.nav_header);// We can now look up items within the header if needed
ImageViewivHeaderPhoto=headerLayout.findViewById(R.id.imageView);

Getting references to the header

Note: Version 23.1.0 of the design support library switches NavigationView to using a RecyclerView and causes NPE (null exceptions) on header lookups unless the header is added at runtime.
If you need to get a reference to the header, you need to use the new getHeaderView() method introduced in the latest v23.1.1 update:

// There is usually only 1 header view.
// Multiple header views can technically be added at runtime.
// We can use navigationView.getHeaderCount() to determine the total number.
ViewheaderLayout=navigationView.getHeaderView(0);

Animate the Hamburger Icon

In order for the hamburger icon to animate to indicate the drawer is being opened and closed, we need to use the ActionBarDrawerToggle class.

protectedvoidonCreate(BundlesavedInstanceState){// Set a Toolbar to replace the ActionBar.
toolbar=(Toolbar)findViewById(R.id.toolbar);setSupportActionBar(toolbar);// Find our drawer view
mDrawer=(DrawerLayout)findViewById(R.id.drawer_layout);drawerToggle=setupDrawerToggle();// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);}privateActionBarDrawerTogglesetupDrawerToggle(){// NOTE: Make sure you pass in a valid toolbar reference. ActionBarDrawToggle() does not require it
// and will not render the hamburger icon without it.
returnnewActionBarDrawerToggle(this,mDrawer,toolbar,R.string.drawer_open,R.string.drawer_close);}

Next, we need to make sure we synchronize the state whenever the screen is restored or there is a configuration change (i.e screen rotation):

// `onPostCreate` called when activity start-up is complete after `onStart()`
// NOTE 1: Make sure to override the method with only a single `Bundle` argument
// Note 2: Make sure you implement the correct `onPostCreate(Bundle savedInstanceState)` method.
// There are 2 signatures and only `onPostCreate(Bundle state)` shows the hamburger icon.
@OverrideprotectedvoidonPostCreate(BundlesavedInstanceState){super.onPostCreate(savedInstanceState);// Sync the toggle state after onRestoreInstanceState has occurred.
drawerToggle.syncState();}@OverridepublicvoidonConfigurationChanged(ConfigurationnewConfig){super.onConfigurationChanged(newConfig);// Pass any configuration change to the drawer toggles
drawerToggle.onConfigurationChanged(newConfig);}

We also need to change the onOptionsItemSelected() method and allow the ActionBarToggle to handle the events.

The ActionBarToggle will perform the same function done previously but adds a bit more checks and allows mouse clicks on the icon to open and close the drawer. See the source code for more context.

One thing to note is that the ActionBarDrawerToggle renders a custom DrawerArrowDrawable for you for the hamburger icon.

Also, make sure to be using android.support.v7.app.ActionBarDrawerToggle version. The android.support.v4.app.ActionBarDrawerToggle has been deprecated.

Making Status Bar Translucent

To have the status bar translucent and have our drawer slide over it, we need to set android:windowTranslucentStatus to true. Because this style is not available for pre Kitkat devices, we'll add res/values-v19/styles.xml file for API version 19 and onwards. Note: If you modify your res/values/styles.xml directly with this android:windowTranslucentStatus line, you are likely to need to build only for SDK versions 19 or higher, which will obviously limit you from supporting many older devices.

Now if you run your app, you should see the navigation drawer and be able to select between your fragments.

Adding custom views to navigation drawer

One improvement made to the design support library 23.1.0 is the addition of support for custom views for the navigation drawer items. For instance, we can create a custom switch like the navigation drawer from Google Play Movies for one of the rows:

The approach is the same as adding ActionView items to the ActionBar. We simply need to define a separate layout such as the following snippet. We will call this file action_view_switch.xml:

You can attach events directly in XML so long as your Activity will implement the method. To add an event handling to the toggle switch programmatically through Java, you will need to first get the menu instance and get access to the corresponding ActionView:

Often these are unnecessary but check them out to see the functionality they provide.

Limitations

The current version of the design support library does come with its limitations. The main issue is with the system that highlights the current item in the navigation menu. The itemBackground attribute for the NavigationView does not handle the checked state of the item correctly: somehow either all items are highlighted or none of them are. This makes this attribute basically unusable for most apps.

Alternative to Fragments

Although many navigation drawer examples show how fragments can be used with the navigation drawer, you can also use a RelativeLayout/LinearLayout if you wish to use the drawer as an overlay to your currently displayed Activity.