Easy Navigation Drawer with Design Support Library

In Google I/O 2015, a lot of new stuff was revealed. One particular thing that caught my eye was the release of Android’s Design Support Library, which I found out thanks to Chris Banes’ tweet.

I’ll show you how to create a Material Design Navigation Drawer almost effortlessly, how to handle Drawer click events and orientation changes too!

What is the new Design Support Library in Android?

Before we get to that, I feel its best if we get comfortable with what the Design support library actually is.

With a little help from the new Android Design Support Library, we’re bringing a number of important material design components to all developers and to all Android 2.1 or higher devices- android-developers.blogspot.in

It includes components such as a NavigationView for Drawer, Floating Action Buttons, Snackbar, Tabs and a motion and scroll framework as well.

Navigation Drawer- then and now

Earlier making a Navigation Drawer in Android, took considerable effort and with the arrival of Material Design, including a header view and stuff, things got even harder.

navigation drawer google+ material design

Design Support Library, Our Savior

To make lives easier we needed to rely on external libraries to create a Material Design Navigation Drawer in Android (unless you were brave enough to attempt it yourself). But thanks to Design Support library, this is now very simple to do.

Let’s get started making an awesome Material Design Navigation Drawer for our Android app.

icon icon

Using the Design support library

We’ll start off by adding its dependency in Gradle.

compile 'com.android.support:design:22.2.0'

Since the library depends on the AppCompat and support-v4 libraries, we can replace those two dependencies with JUST this.

Navigation Drawer Layout

Go to your activity XML layout and structure your DrawerLayout like this:

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="true">

    <!-- your content layout -->

    <android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:fitsSystemWindows="true"
        app:headerLayout="@layout/drawer_header"
        app:menu="@menu/drawer" />

</android.support.v4.widget.DrawerLayout>

With this as the base, let’s add in our Toolbar layout with:  <include layout="@layout/toolbar" />. Remember we can open the Drawer by tapping the burger icon as well, and for that we need a Toolbar.

Note the new NavigationView. This comes from the Design support library. You can define its headerLayout and must assign a menu resource for it.

The fitsSystemWindows attribute tells Android to draw this view behind the Status Bar. So when you open the Navigation Drawer, it appears behind a transparent Status Bar.

Drawer Menu

This is like your regular menu resource you use for your Toolbar ActionBar, but with a slight change. All menu items must be in a group. (Unless you want to categorize your menu items in groups). It’s checkableBehaviour MUST be single.

<menu xmlns:android="http://schemas.android.com/apk/res/android">
    <group android:checkableBehavior="single">
        <item
            android:id="@+id/navigation_item_1"
            android:checked="true"
            android:icon="@drawable/ic_action_clear"
            android:title="Item One" />
        <item
            android:id="@+id/navigation_item_2"
            android:icon="@drawable/ic_action_add"
            android:title="Item Two" />
    </group>

</menu>

Navigation Drawer Divider

If you wish to add a divider between your menu items, then simply add items in another group with a different ID. So all items residing in the second group will be separated from the first by a divider.

Header Layout

For the Drawer’s Header layout, we create another XML layout that contains a simple ImageView and TextView.

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="150dp"
    android:orientation="vertical">

    <ImageView
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:background="@drawable/nav_header_bg"
        android:scaleType="centerCrop" />

    <TextView
        style="@style/TextAppearance.AppCompat.Subhead"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom"
        android:layout_margin="16dp"
        android:text="Your Name Here"
        android:textColor="@android:color/white" />

</FrameLayout>

You could add whatever you need, but I’m going to keep it simple with this.

navigation drawer header view

That is all the XML we’ll be seeing for this post. Let’s dig into some Java now.

Setting up the Activity

Open up your Activity.java. Here we need to:

  1. Initialize the Toolbar
  2. Handle Drawer click events
  3. Handle orientation changes
  4. Introduce the Drawer to 1st time users (via Preference)

1. Initialize the Toolbar

Frankly, I like to keep my onCreate() method free of clutter. So we’ll create a method for this and call it in.

private void setUpToolbar() {
       mToolbar = (Toolbar) findViewById(R.id.toolbar);
       if (mToolbar != null) {
           setSupportActionBar(mToolbar);
       }
   }

2. Set up Navigation Drawer

private void setUpNavDrawer() {
       if (mToolbar != null) {
           getSupportActionBar().setDisplayHomeAsUpEnabled(true);
           mToolbar.setNavigationIcon(R.drawable.ic_drawer);
           mToolbar.setNavigationOnClickListener(new View.OnClickListener() {
               @Override
               public void onClick(View v) {
                   mDrawerLayout.openDrawer(GravityCompat.START);
               }
           });
       }

   }

Here we’re allowing the Toolbar (ActionBar) to display a home as up button, and supplying the icon for it. Then define its click listener where we open the Navigation Drawer upon click. Remember to call this method in onCreate() as well.

3. Handle Drawer click events

While the Drawer opens/ closes using the DrawerLayout as a reference, the click events for the list items (menu) is handled by the NavigationView via its setNavigationItemSelectedListener() method.

mNavigationView.setNavigationItemSelectedListener(new NavigationView.OnNavigationItemSelectedListener() {
           @Override
           public boolean onNavigationItemSelected(MenuItem menuItem) {

               menuItem.setChecked(true);

               switch (menuItem.getItemId()) {
                   case R.id.navigation_item_1:
                       Snackbar.make(mContentFrame, "Item One",                
                           Snackbar.LENGTH_SHORT).show();
                       mCurrentSelectedPosition = 0;
                       return true;
                   case R.id.navigation_item_2:
                       Snackbar.make(mContentFrame, "Item Two", 
                           Snackbar.LENGTH_SHORT).show();
                       mCurrentSelectedPosition = 1;
                       return true;
                   default:
                       return true;
               }
           }
       });

Within the switch case is where we’ll actually be handling our Drawer’s item clicks. I will explain a bit later on why we need to track mCurrentSelectedPosition.

iconicon

If you wish to handle Fragment transactions with your Navigation Drawer, just remember that it stays the same as before. Just below your Toolbar add a FrameLayout like this:

<FrameLayout
        android:id="@+id/nav_contentframe"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_marginTop="?attr/actionBarSize" />

You can handle the fragment transactions under the switch case.

This is all we need to get our Material Style Navigation Drawer with Design support library up and running. But honestly, if you plan on implementing something: Do it good, or don’t bother doing it.

With that being said, that last 2 parts is handling the drawer upon orientation changes (so your app doesn’t crash when you flip the phone) and showing the Drawer for the first time to users (part of the guidelines).

4. Handling Orientation Changes

If the phone orientation changes, the app will redraw or reload the activity to adapt to the new orientation. So when this happens, data existing during the previous load must be held. Loss of this data during the redraw results in a crash.

Remember we used mCurrentSelectedPosition a bit earlier when handling our Drawer clicks? Well, we’re going to use that now. This is used to track which item on the Drawer was clicked, by storing its position.

If you don’t follow what I’m saying, with what we’ve done until now, go ahead and run your app. Tap any item on the Drawer apart from the default and flip your phone in landscape. You’ll note that what you selected is reset. We’re going to prevent that.

To handle the state before and after the orientation change, we need to implement two methods:

public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putInt(STATE_SELECTED_POSITION, mCurrentSelectedPosition);
}

Note that STATE_SELECTED_POSITION is our key. We’ll transfer mCurrentSelectedPosition‘s value to a Bundle and save it. Upon restoring, we recover that value from the bundle using the key.

Before we change the orientation, we want to save the last position we clicked. Once that’s done, we need to restore the data on reload.

protected void onRestoreInstanceState(Bundle savedInstanceState) {
        super.onRestoreInstanceState(savedInstanceState);
        mCurrentSelectedPosition = savedInstanceState.getInt(STATE_SELECTED_POSITION, 0);
        Menu menu = mNavigationView.getMenu();
        menu.getItem(mCurrentSelectedPosition).setChecked(true);
    }

We retrieve our stored position data via a Bundle and then make that menu item checked.

In your Activity’s onCreate() method, immediately after initializing your views and before calling your setup methods, add this.

if (savedInstanceState != null) {
           mCurrentSelectedPosition =  
             savedInstanceState.getInt(STATE_SELECTED_POSITION);
           mFromSavedInstanceState = true;
}

With this our Navigation Drawer will now handle orientation changes properly without crashes.

If you have no idea about what these methods mean, then this should give you a better idea.

4. Introduce Drawer First Time

When a user launches an app for the first time, we must open the drawer and show it to them. We’ll do this using Preference.

First off, add these two methods in your Activity.

public static void saveSharedSetting(Context ctx, String settingName, String settingValue) {
       SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
       SharedPreferences.Editor editor = sharedPref.edit();
       editor.putString(settingName, settingValue);
       editor.apply();
   }

   public static String readSharedSetting(Context ctx, String settingName, String defaultValue) {
       SharedPreferences sharedPref = ctx.getSharedPreferences(PREFERENCES_FILE, Context.MODE_PRIVATE);
       return sharedPref.getString(settingName, defaultValue);
   }

Preference file is  private static final String PREFERENCES_FILE = "yourappname_settings";

We’ll store a simple true/ false value in our Preference settings file and use that to know whether the app is launched for the first time or not.

Initially read your preference with this:

mUserLearnedDrawer = Boolean.valueOf(readSharedSetting(this, PREF_USER_LEARNED_DRAWER, "false"));

PREF_USER_LEARNED_DRAWER is my key (String type) which I use to fetch my Preference value.

Android Material UI Template 8 in 1 CodeCanyon

Now, go to where you initialize your DrawerLayout (setUpNavDrawer() method) and add these lines:

if (!mUserLearnedDrawer) {
           mDrawerLayout.openDrawer(GravityCompat.START);
           mUserLearnedDrawer = true;
           saveSharedSetting(this, PREF_USER_LEARNED_DRAWER, "true");
       }

If the user hasn’t learned about the Drawer (not seen it yet), then open the Drawer and set the learned preference to true.

We now have a complete working Navigation Drawer:

navigation drawer material design

Note the deliberate slow down while closing the Drawer. The Status Bar overlaps the Navigation Drawer. This is quite easy to achieve. You just need to add this to your theme in v-21 styles.xml.

<item name="android:windowTranslucentStatus">true</item>

Check out the working sample over at my GitHub.


That’s it. I know the post was pretty long, but let’s just see what we’ve achieved:

We’ve managed to create a fully working Material Design Navigation Drawer with Design Support library in Android, which handles orientation changes perfectly and also greets users for the first time on app launch!

While that was a mouthful, I’m sure you realize that this is actually a walk in the park considering how hard a Material Design Navigation Drawer was to create in the past! 🙂

Do subscribe (below) or  for instant updates as I continue to bring you more awesome content!

App developer with an eye for design. Loves to create apps with good UI/ UX that doesn’t annoy people. In his spare time, he likes to draw and paint.
Subscribe to stay updated
You'll be first to know about new articles and more. They're sent straight to your inbox!
No Spam, no BS. Promise. You can unsubscribe anytime.

Suleiman

App developer with an eye for design. Loves to create apps with good UI/ UX that doesn't annoy people. In his spare time, he likes to draw and paint.

You may also like...

  • Boundavan Vang

    How to custom font NavigationView menu item in Xamarin android ?

  • Kushal Pandey

    In github sample you are using two package import named, com.amulyakhare.textdrawable.TextDrawable and com.amulyakhare.textdrawable.util.ColorGenerator, could you please tell me the exact working for these imports, also if it is possible could you please share them.

  • Shrey Khanduri

    How can i add sub menu in navigation drawer items ?

  • Rajesh Kumar

    How i can add another text in same row. Item can have only icon and title. I need 3rd text like below image

    • I’m not able to view that image clearly. Could you upload it somewhere else and link back here?

      • Rajesh Kumar

        it is just one icon,string and another string.

      • Since Support Library v23.1, this is possible with NavigationView.
        Use app:actionLayout or MenuItemCompat.setActionView()

  • raja guru

    I was tried in my project but nothing to show on my home Dashboard fragment How i can display the dashboard fragment,

    • Hi raja,
      Not quite sure I follow what you said. Could you please elaborate?

      • raja guru

        1st one is when i add the fragment in this project it,s not shows the full screen Then i can’t shows anything for the dashboard (dashboard like activity_main.xml) and u r post is add the background color to all fragments u also see the error.if u give u mail id i have attach the my project it shows the full error plz help me…………..

      • Please post relevant code snippets and error log on StackOverflow, so I can take a look.

  • Sidney van der Stoep

    Great tutorial, it helped me creating my first navigation drawer for my dive locations app:)! But i’ve been puzzling for days to integrate the tabs animation from you other tutorial. This I can not manage.

    If I add this item

    case R.id.navigation_item_5:
    title = getString(R.string.title_dieren);
    intent = new Intent(NavDrawerActivity.this, TabsHeaderActivity.class);
    startActivity(intent);
    Clicking it brings you to the TabsHeaderActivity but I would like to get it in the same view and not start a new activity. Adding new fragments isn’t a problem they all open in the nav_contentframe and the drawermenu stays visible.

    I hope you can point me in the right direction

  • dian

    how if I want to add such expandable listview in navigation drawer? so that my drawer menu has submenus?

  • Madhavi Gullipalli

    Nice Tutorial…is it possible to transfer data from one fragment to other in Navigation drawer?

    • Yes its possible. Get data from Fragment A into Activity, then pass it to Fragment B using it’s setArguments() method.

      • Madhavi Gullipalli

        Thank u so much …

  • Half Moon

    Find Best Navigation UI Design: Click Here

    • Very creative designs. Thanks for the curated list.

  • Half Moon

    nice

  • davide

    nice, is possible use transparent background for main activity?

    • Yes you can. But it doesn’t matter since your MainActivity would inflate a Fragment I presume?

  • Witalo Benicio

    Im getting a ResourceNotFoundException at the NavigationView but i have the support design updated.

    • Witalo Benicio

      If anyone get this error just put
      app:itemTextColor=”@color/textColor”
      inside your NavigationView in xml.

    • Many of the default Android resources in the support libraries became private after the update, preventing access. Simply switch these with your own resources and you won’t face any error.

  • Ashwini Bhat

    how to add Navigation item dynamically?

    Example:when
    user click on button dialogue box open and enter some text and click OK
    whatever user enters has to show in navigation item…am using Menu to
    add navigation item..how can I do with menu please help me.Thank you

  • Poonam Kukreti

    Is it possible to change the tiltle of side drawer with if or else condition?

    • Which ‘title’ are you referring to? If it’s the “Your name here” part, that’s defined in my XML. You can reference that TextView and rename it to anything you want.

      • Poonam Kukreti

        No, As i want to change “Item One” to “Disqus” with some condition .is it possible to do that ?

      • if(condition){
        menuItem.setTitle(“Disqus”);

        }

      • Poonam Kukreti

        Thank you , One more issue i am facing , as i am using two fragments, both have tab sliders calling as a fragment . when i go to one fragment to another .fragments are going blank no data is there. do you know what is the problem ?

  • Thanks for tutorial…it was very helpful….

  • tommypacker

    Hey, how would I open up a preferencesFragment using this setup? Thanks!

  • tommypacker

    So I switch fragments every time a nav drawer item is selected. How would I retain what fragment is selected? Thanks!

    • tommypacker

      Nvm, I figured it out

  • Felix Maximilian Hoffer

    @suleiman19:disqus Hey thanks, this helped me a lot! But I have a problem, I want to recreate the Branded Splash Screens that Google recently added to their Apps. Do you know how they do them?

    • Glad it helped you Felix. Actually, I’m coming up with a post on just that. While there is no ‘official’ way of doing this, I hope my approach should do it justice.

      • Felix Maximilian Hoffer

        Actually I thought that you would 😉 But I wanted to be sure. That would be awsome! Another little question, is it possible with your Example that the Navigation Drawer doesn’t overlap the Toolbar? And if there is, is it a Question of Interest or doesn’t it match with the Material Design Samples? Because I implemented the Icon Toggle, and I want it to be seen ;)))

      • I get what you mean Felix. That icon toggle is pretty cool and I totally understand if you want it to be seen! There are many similar queries on Stack Overflow with a solution: http://stackoverflow.com/questions/26985270/navigation-drawer-below-toolbar

        Hopefully this should get you sorted!

      • Felix Maximilian Hoffer

        Okay, well the reply in the post suggests that it is against the material design guidelines. Well, thanks for your help anyway! Looking forward to your splah screen post!

      • The Material Design specify guidelines upon which you can build your apps. These are not hard rules that you MUST follow. Don’t let that restrict creativity.
        A drawer below the Toolbar is absolutely fine 😉
        In fact, in the early days of Material Design, Google itself had done the same for their Play Store app.

      • Felix Maximilian Hoffer

        I know that they had both variants. Okay I asked my company partners about their opinion 😉 Thanks a lot

  • Felix Maximilian Hoffer

    Thank you too, I was really happy that I found you. But I have one question, what do I have to to, if I want to close the Navigation Drawer after a click?

  • Syed Ali Naqi

    I m getting error:

    07-26 21:51:08.283 6136-6140/com.i10studios.websiteinformer E/dalvikvm﹕ adjustAdaptiveCoef max=4194304, min=1048576, ut=568

    07-26 21:51:08.684 6136-6136/com.i10studios.websiteinformer E/AndroidRuntime﹕ FATAL EXCEPTION: main

    java.lang.NullPointerException

    at android.support.design.internal.NavigationMenuItemView.setIcon(NavigationMenuItemView.java:113)

    at android.support.design.internal.NavigationMenuItemView.initialize(NavigationMenuItemView.java:72)

    at android.support.design.internal.NavigationMenuPresenter$NavigationMenuAdapter.getView(NavigationMenuPresenter.java:305)

    at android.widget.HeaderViewListAdapter.getView(HeaderViewListAdapter.java:230)

    at android.widget.AbsListView.obtainView(AbsListView.java:2603)

    at android.widget.ListView.makeAndAddView(ListView.java:1840)

    at android.widget.ListView.fillDown(ListView.java:681)

    at android.widget.ListView.fillFromTop(ListView.java:742)

    at android.widget.ListView.layoutChildren(ListView.java:1661)

    at android.widget.AbsListView.onLayout(AbsListView.java:2426)

    at android.view.View.layout(View.java:14905)

    at android.view.ViewGroup.layout(ViewGroup.java:4601)

    at android.widget.FrameLayout.onLayout(FrameLayout.java:448)

    at android.view.View.layout(View.java:14905)

    at android.view.ViewGroup.layout(ViewGroup.java:4601)

    at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:931)

    at android.view.View.layout(View.java:14905)

    at android.view.ViewGroup.layout(ViewGroup.java:4601)

    at android.widget.FrameLayout.onLayout(FrameLayout.java:448)

    at android.view.View.layout(View.java:14905)

    at android.view.ViewGroup.layout(ViewGroup.java:4601)

    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1694)

    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1552)

    at android.widget.LinearLayout.onLayout(LinearLayout.java:1465)

    at android.view.View.layout(View.java:14905)

    at android.view.ViewGroup.layout(ViewGroup.java:4601)

    at android.widget.FrameLayout.onLayout(FrameLayout.java:448)

    at android.view.View.layout(View.java:14905)

    at android.view.ViewGroup.layout(ViewGroup.java:4601)

    at android.widget.LinearLayout.setChildFrame(LinearLayout.java:1694)

    at android.widget.LinearLayout.layoutVertical(LinearLayout.java:1552)

    at android.widget.LinearLayout.onLayout(LinearLayout.java:1465)

    at android.view.View.layout(View.java:14905)

    at android.view.ViewGroup.layout(ViewGroup.java:4601)

    at android.widget.FrameLayout.onLayout(FrameLayout.java:448)

    at android.view.View.layout(View.java:14905)

    at android.view.ViewGroup.layout(ViewGroup.java:4601)

    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:2213)

    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:2027)

    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1237)

    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5162)

    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:791)

    at android.view.Choreographer.doCallbacks(Choreographer.java:591)

    at android.view.Choreographer.doFrame(Choreographer.java:561)

    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:777)

    at android.os.Handler.handleCallback(Handler.java:725)

    at android.os.Handler.dispatchMessage(Handler.java:92)

    at android.os.Looper.loop(Looper.java:176)

    at android.app.ActivityThread.main(ActivityThread.java:5317)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:511)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:1102)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:869)

    at dalvik.system.NativeStart.main(Native Method)

    • The error clearly says its a NullPointerException. Check if you’re passing your navigation icon correctly. It pinpoints to the corresponding lines of code in your NavigationMenuItemView.java
      You might want to start there.

  • Tudor

    I like how this uses a menu.xml for the navigation drawer. I’ve implemented this and love the simplicity of a menu.xml over using listview. However, I can’t figure out how to group items using a divider between them. Say you have four navigation items and one for settings, you’d want a divider line according to material specs above the item for settings. Any idea how achieve this? Thank you!

    • Hi Tudor,
      Glad we share similar opinions on the simplicity of a menu resource.

      For a divider use:

      // Your navigation items here

      All items inside this item tag will fall under a divider.
      Good luck.

      • Tudor

        Hi, thank you.
        I did tried this (was after writing the comment, sorry) but it gives me the unwanted subheader I couldn’t get rid of. If there is any way to remove or to at least hide the subheader. Giving it blank title will hide it but it will still push down the menu making unwanted top margin/padding.

        http://stackoverflow.com/questions/31559705/divider-in-navigation-drawer-using-a-xml-menu

      • Have seen your question on StackOverflow. Why not simply remove this:

      • Tudor

        But it’s the header I don’t want.
        item – item – divider – item – item – item etc.. no headers or subheaders

      • Simply add your items in another group. Remember to assign a uniqute id to each group like this:

        //items here

        //items below divider here

        This should work for you. Have tried it myself.
        Any other issues you run into, this link should be of help: http://stackoverflow.com/questions/30625280/how-to-create-a-simple-divider-in-the-new-navigationview

      • Tudor

        Wow, I didn’t add id to the groups when I tried that. Without id one get no divider.
        Thank you!

  • Adrian Vovk

    How to customize the selected color? For the text +icon I mean

    I want to keep the default colors but change the selected ones

    • If you take a look at my project on Git, you can see how the theme is setup in styles.xml
      The navigation drawer automatically uses colorPrimary to highlight the items on click.

      • Adrian Vovk

        Is there a way to switch that to color accent?

      • You can do that using a ColorStateList (similar to a selector but changes color rather than drawable)
        mNavigationView.setItemTextColor(ColorStateList resource);

  • gebrielabebe

    You said “All menu items must be in a group”. But what if I am loading the menu items from internet? How can I implement that?

    • Why would you be loading the menu items from the internet? The menu items for a Drawer will be constant, so you can preload it from a menu resource.

      • gebrielabebe

        Because my menu items are dynamic. I have a json server to get the items from.

      • While fetching the data into a list will not be a problem. I dont find any methods to pass them into a menu resource. So i suggest you inflate a RecyclerView with an adapter populated with your JSON data.

        You can fetch your JSON object strings and store them in an ArrayList via list.add();

        The downside to this approach is you have to manually implement your drawer layout (there are many libraries to simplify this process). The advantage is customization 🙂

  • farhan patel

    how to include drawer in each activity?

    • Create a BaseActivity which holds the Navigation Drawer.

      Instead of making each of your Activity extend ‘AppCompatActivity’, all Activities for which you want the Drawer, extend ‘BaseActivity’.

  • Gobi Viv

    how to close the drawer when the orientation changes?????

  • Jaskaran Singh

    sir, i am having an issue.
    not able to select nav drawer items and snack bar is not appearing.

    • Hi Jaskaran,
      I have mentioned how to handle the click events in the post. They key is make the list items behave as checkable views so they stay selected on touch.

      Could you post your code on GitHub or StackOverflow, where I can have a look?

  • VG

    HI How to add Notification Counter on right side of Navigation view item?

    • Hey there,
      I recently addressed the same question on G+
      Please take a look at my first reply to Alex M.

      It will help you with a more comprehensive reply.
      https://plus.google.com/110183172030290491634/posts/AL8WJAHTaH3

      However, long answer short 😉 for custom requirements, use this:
      https://github.com/neokree/MaterialNavigationDrawer

      Cheers

      • VG

        Thanks for reply but I was only interested in solution using New design library.Coz I have already progressed with it in my project and I am facing only this issue.So Can you direct me on this?

      • Sorry to disappoint, but I don’t think there is any way to add a counter, at least for now. The Design library is relatively new and already has some noticeable bugs which will take time to fix.

        If you take a closer look at the NavigationView, the list needed for the drawer is supplied as a menu resource via ‘app:menu’. If that was a custom layout like the header ‘app:headerLayout’, then it could be possible.

        So the only solution I could recommend to you as of now, is to supply your own custom list for the Drawer.

  • albertvaka

    That was helpful (and fast, right after the announcement). Thanks!

    • Thank you. I’m glad you found it useful.

  • Jeremy Kolb

    Do we still need to use `ActionBarDrawerToggle`?

    • No, not required. The toolbar’s ‘setNavigationOnClickListener’ can be used to open the drawer.

  • To save the drawer state, you should use https://developer.android.com/reference/android/support/design/widget/NavigationView.SavedState.html instead of saving the index.

    • Hey Kernald, thanks for that. However, I find saving the index suitable for this purpose, as a regular Drawer would have Fragments that would take care of the saved instance.
      Could you show how ‘NavigationView.SavedState’ would come into play?

      • Well actualy NavigationView reimplements

        onRestoreInstanceState and

        onSaveInstanceState so you shouldn’t need to do anything. I didn’t tried it yet, but it should be called internaly and save its state by itself… Sorry about that, I should have checked that it works before commenting.

      • Thanks for the info! Nah, not a problem. 🙂

Subscribe to stay updated
You'll be first to know about new articles and more. They're sent straight to your inbox!
No Spam, no BS. Promise. You can unsubscribe anytime.
Gradle setup, ProGuard rules, Material Design palette, metrics and much more

FREE Material Design Starter Project

For more details, click on the below link.
GET IT NOW FOR ANDROID STUDIO!
Download FREE
STARTER PROJECT
Material Design Template Project for Android Studio
DOWNLOAD STARTER PROJECT
Android O is finally here!
Ready your Apps to get an advantage on Play Store.