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.

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.

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.

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!

Suleiman

Product Designer who occasionally writes code.

You may also like...

92 Responses

  1. davide says:

    nice, is possible use transparent background for main activity?

  2. Witalo Benicio says:

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

    • Witalo Benicio says:

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

    • Suleiman19 says:

      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.

  3. Ashwini Bhat says:

    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

  4. Poonam Kukreti says:

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

    • Suleiman19 says:

      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 says:

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

      • Suleiman19 says:

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

        }

      • Poonam Kukreti says:

        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 ?

  5. Thanks for tutorial…it was very helpful….

  6. tommypacker says:

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

  7. tommypacker says:

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

  8. Felix Maximilian Hoffer says:

    @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?

    • Suleiman19 says:

      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 says:

        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 ;)))

      • Suleiman19 says:

        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 says:

        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!

      • Suleiman19 says:

        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 says:

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

  9. Felix Maximilian Hoffer says:

    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?

  10. Syed Ali Naqi says:

    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)

    • Suleiman19 says:

      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.

Leave a Reply

Your email address will not be published. Required fields are marked *