How To Make Material Design Navigation Drawer With Header View

12:26 , 190 Comments

One of the most evident changes when the material design came out and I got my hands on was the new Navigation Drawer, The Hamburger toggle icon animation seemed very beautiful, The Overlapping drawer on status bar also seemed nice effect and so we are going to learn how to make a Navigation Drawer in this tutorial, with that effect and we are going to use the new RecyclerView for making the list view with the header (just like Gmail app's Navigation Drawer) in the sliding drawer, So let's begin.


Prerequisites

We are going to make the 
Navigation Drawer over the Action Bar/ App Bar we made in the previous post. It isn't completely necessary to read the previous post where I show how to make a material design App Bar but I strongly recommend you to read it once.

Requirements

1. Android Studio 1.0.1 (Latest at the time of writing this post)


2. CircleImage Library (which is used in the header view for the profile picture). Add this library in your gradel build by including the following dependency

compile 'de.hdodenhof:circleimageview:1.2.1'


3. Appcombat v7-21 Support Library As I have explained in my earlier post, If you are running over new Android studio you don't need to add a compiled dependency of appcombat v7 21 as the Android Studio takes care of it. The next thing you need to add in your gradel build is compiled dependency for RecyclerView. To do that add the following line in your build.gradel file.

compile 'com.android.support:recyclerview-v7:21.0.+' 


Let's Understand How the Navigation Drawer Works




To make a Navigation Drawer, you have to initiate it in the XML file of the activity on which you want to implement the material design sliding drawer. To initiate the Navigation Drawer we need to use the XML tag as shown below and as with any other view you have to set the layout attributes such as Height, Width, and Id etc. Drawer Layout should have two child views

First Child - Main Content
Second Child - Sliding Drawer Content

For Example look at the structure below
<android.support.v4.widget.DrawerLayout>

<RelativeLayout></RelativeLayout> - Main Content (First Child)
 <RecyclerView></RecyclerView> - Sliding Drawer Content (Second Child)

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

Now you have to decide from which side of the app you want your Navigation Drawer to slid in the layout, Depending on your choice set the layout_gravityt of the child view to either left if you want the drawer to slide from left or right if you want it to slide from right.

Steps To Make A Material Design Navigation Drawer 

First let's see what we are trying to make



As you can see we have a sliding drawer which slides from the left side of the app and overlaps the translucent status bar, inside the drawer we have a header view which contains a circular view for the profile picture and two Text Views, below that there is our List view with icons.

As we are making a navigation drawer over the Action Bar/App Bar we made in the earlier post what we have with us while we start out, looks something like this

app bar

Just a App Bar with icons on it as we made this in my previous post

Now lets start to code our Navigation Drawer


1. First open up our activity_main.xml file from res folder and add a DrawerLayout as the root view of the app and inside the drawer layout add the App bar which is done by adding the include tag inside the first child of your drawer layout (in my case its the linear layout) now as the drawer layout is your root layout and you have included the App bar inside the drawers first child, all this makes sure the drawer slides over the App bar as we wanted. You would get the clear understanding after you see the layout file.  

This is how the activity_main.xml looks like



<?xml version="1.0" encoding="utf-8"?>

<android.support.v4.widget.DrawerLayout 

    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/DrawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:elevation="7dp">


    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">


        <include
            android:id="@+id/tool_bar"
            layout="@layout/tool_bar">
        </include>

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Hello World" />

    </LinearLayout>


    <android.support.v7.widget.RecyclerView
        android:id="@+id/RecyclerView"
        android:layout_width="320dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"

        android:background="#ffffff"
        android:scrollbars="vertical">

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


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


2. Now let's define how a single row in the navigation drawer list going to look like, For that make a new layout file by going to res=>layouts and make a new layout file and name it item_row.xml. Now as we want to have a icon and a title in in every row of our list we would put an image view and TextView inside a RelativeLayout.

Here is how the item_row.xml looks like


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:layout_height="wrap_content"
    android:background="#ffffff"
    android:orientation="horizontal">


    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:id="@+id/rowIcon"
        android:paddingLeft="16dp"
        android:src="@drawable/ic_launcher"/>

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:paddingLeft="12dp"
        android:paddingTop="4dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:text="Medium Text"
        android:id="@+id/rowText" />

</LinearLayout>


3. Now we need to define our Header View and for that we make a new layout file by going to  res=>layouts and create a new layout file, name the new layout file as header.xml. Now our header view has one circular image view for profile picture and two text views, adding text view is easy and to add circular profile picture I have used a library called CircleImageView as i have told earlier, and finally to make things look good I have given a background image to the header view. for better understanding look at the layout file

This is how the header.xml looks like.
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="178dp"
    android:background="@drawable/background_poly"
    android:orientation="vertical"
    android:weightSum="1">



    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="56dp"
        android:orientation="vertical"
        android:layout_alignParentBottom="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true">

        <TextView
            android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:textColor="#ffffff"
            android:text="Akash Bangad"
            android:textSize="14sp"
            android:textStyle="bold"

            />

        <TextView
            android:id="@+id/email"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textColor="#ffffff"
            android:layout_marginLeft="16dp"
            android:layout_marginTop="5dp"
            android:text="akash.bangad93@gmail.com"
            android:textSize="14sp"
            android:textStyle="normal"

            />
    </LinearLayout>

    <de.hdodenhof.circleimageview.CircleImageView
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:src="@drawable/aka"
        android:layout_marginLeft="16dp"
        android:layout_marginTop="38dp"
        android:id="@+id/circleView"
       />
</RelativeLayout>

4. The next step is to put icons and images in our projects Drawables folder, As always i have downloaded icons from www.icons4android.com which is one of the 5 tools I recommend everyone to use, Copied those icons and pasted them in drawable folder inside my project. I have also added two pictures to the project one is for the header background and other is for the profile picture.

5. Now we have all the layouts ready, We have to initiate everything in code now. So let's look at MainActivity.java I have put up the comments to help you understand what's going on 


package com.android4devs.navigationdrawer;

import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;


public class MainActivity extends ActionBarActivity {

    //First We Declare Titles And Icons For Our Navigation Drawer List View
    //This Icons And Titles Are holded in an Array as you can see

    String TITLES[] = {"Home","Events","Mail","Shop","Travel"};
    int ICONS[] = {R.drawable.ic_home,R.drawable.ic_events,R.drawable.ic_mail,R.drawable.ic_shop,R.drawable.ic_travel};

    //Similarly we Create a String Resource for the name and email in the header view
    //And we also create a int resource for profile picture in the header view

    String NAME = "Akash Bangad";
    String EMAIL = "akash.bangad@android4devs.com";
    int PROFILE = R.drawable.aka;

    private Toolbar toolbar;                              // Declaring the Toolbar Object

    RecyclerView mRecyclerView;                           // Declaring RecyclerView
    RecyclerView.Adapter mAdapter;                        // Declaring Adapter For Recycler View
    RecyclerView.LayoutManager mLayoutManager;            // Declaring Layout Manager as a linear layout manager
    DrawerLayout Drawer;                                  // Declaring DrawerLayout

    ActionBarDrawerToggle mDrawerToggle;                  // Declaring Action Bar Drawer Toggle




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

    /* Assinging the toolbar object ot the view
    and setting the the Action bar to our toolbar
     */
    toolbar = (Toolbar) findViewById(R.id.tool_bar);
    setSupportActionBar(toolbar);




        mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View

        mRecyclerView.setHasFixedSize(true);                            // Letting the system know that the list objects are of fixed size

        mAdapter = new MyAdapter(TITLES,ICONS,NAME,EMAIL,PROFILE);       // Creating the Adapter of MyAdapter class(which we are going to see in a bit)
                                                                         // And passing the titles,icons,header view name, header view email,
                                                                         // and header view profile picture

        mRecyclerView.setAdapter(mAdapter);                              // Setting the adapter to RecyclerView

        mLayoutManager = new LinearLayoutManager(this);                 // Creating a layout Manager

        mRecyclerView.setLayoutManager(mLayoutManager);                 // Setting the layout Manager


        Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);        // Drawer object Assigned to the view
        mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                // code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
                // open I am not going to put anything here)
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                // Code here will execute once drawer is closed
            }



    }; // Drawer Toggle Object Made
        Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
        mDrawerToggle.syncState();               // Finally we set the drawer toggle sync State

    }


    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();

        //noinspection SimplifiableIfStatement
        if (id == R.id.action_settings) {
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}



6. Now we have to make the adapter fot the header view and list view in our drawer, earlier adding headers was as easy as calling addHeaderView() function from the object of list view but with recycler view things have changed and now we have to make changes to our adapter to make it understand that we want the first row of the list to be our header, we do that by inflating the header.xml for the first row and item_row.xml for the rest of the rows. look at the code where I have explained the process with appropriate comments.

So this is how the MyAdapter.java looks like

package com.android4devs.navigationdrawer;

import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

/**
 * Created by hp1 on 28-12-2014.
 */
public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
    
    private static final int TYPE_HEADER = 0;  // Declaring Variable to Understand which View is being worked on 
                                               // IF the view under inflation and population is header or Item 
    private static final int TYPE_ITEM = 1;

    private String mNavTitles[]; // String Array to store the passed titles Value from MainActivity.java
    private int mIcons[];       // Int Array to store the passed icons resource value from MainActivity.java
    
    private String name;        //String Resource for header View Name
    private int profile;        //int Resource for header view profile picture
    private String email;       //String Resource for header view email  


    // Creating a ViewHolder which extends the RecyclerView View Holder
    // ViewHolder are used to to store the inflated views in order to recycle them

    public static class ViewHolder extends RecyclerView.ViewHolder {
        int Holderid;       
        
        TextView textView;  
        ImageView imageView;
        ImageView profile;
        TextView Name;
        TextView email;
       

        public ViewHolder(View itemView,int ViewType) {                 // Creating ViewHolder Constructor with View and viewType As a parameter
            super(itemView);
            
           
            // Here we set the appropriate view in accordance with the the view type as passed when the holder object is created
            
            if(ViewType == TYPE_ITEM) {
                textView = (TextView) itemView.findViewById(R.id.rowText); // Creating TextView object with the id of textView from item_row.xml
                imageView = (ImageView) itemView.findViewById(R.id.rowIcon);// Creating ImageView object with the id of ImageView from item_row.xml
                Holderid = 1;                                               // setting holder id as 1 as the object being populated are of type item row
            }
            else{


                Name = (TextView) itemView.findViewById(R.id.name);         // Creating Text View object from header.xml for name 
                email = (TextView) itemView.findViewById(R.id.email);       // Creating Text View object from header.xml for email
                profile = (ImageView) itemView.findViewById(R.id.circleView);// Creating Image view object from header.xml for profile pic
                Holderid = 0;                                                // Setting holder id = 0 as the object being populated are of type header view
            }
        }

        
    }



    MyAdapter(String Titles[],int Icons[],String Name,String Email, int Profile){ // MyAdapter Constructor with titles and icons parameter
                                            // titles, icons, name, email, profile pic are passed from the main activity as we
        mNavTitles = Titles;                //have seen earlier
        mIcons = Icons;
        name = Name;
        email = Email;
        profile = Profile;                     //here we assign those passed values to the values we declared here
        //in adapter



    }



    //Below first we ovverride the method onCreateViewHolder which is called when the ViewHolder is
    //Created, In this method we inflate the item_row.xml layout if the viewType is Type_ITEM or else we inflate header.xml
    // if the viewType is TYPE_HEADER
    // and pass it to the view holder

    @Override
    public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {

        if (viewType == TYPE_ITEM) {
            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_row,parent,false); //Inflating the layout

            ViewHolder vhItem = new ViewHolder(v,viewType); //Creating ViewHolder and passing the object of type view

            return vhItem; // Returning the created object

            //inflate your layout and pass it to view holder

        } else if (viewType == TYPE_HEADER) {

            View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header,parent,false); //Inflating the layout

            ViewHolder vhHeader = new ViewHolder(v,viewType); //Creating ViewHolder and passing the object of type view

            return vhHeader; //returning the object created

            
        }
        return null;

    }

    //Next we override a method which is called when the item in a row is needed to be displayed, here the int position
    // Tells us item at which position is being constructed to be displayed and the holder id of the holder object tell us 
    // which view type is being created 1 for item row
    @Override
    public void onBindViewHolder(MyAdapter.ViewHolder holder, int position) {
        if(holder.Holderid ==1) {                              // as the list view is going to be called after the header view so we decrement the 
                                                              // position by 1 and pass it to the holder while setting the text and image
            holder.textView.setText(mNavTitles[position - 1]); // Setting the Text with the array of our Titles
            holder.imageView.setImageResource(mIcons[position -1]);// Settimg the image with array of our icons
        }
        else{

            holder.profile.setImageResource(profile);           // Similarly we set the resources for header view
            holder.Name.setText(name);
            holder.email.setText(email);
        }
    }

    // This method returns the number of items present in the list
    @Override
    public int getItemCount() {
        return mNavTitles.length+1; // the number of items in the list will be +1 the titles including the header view.
    }

    
    // Witht the following method we check what type of view is being passed 
    @Override
    public int getItemViewType(int position) {  
        if (isPositionHeader(position))
            return TYPE_HEADER;

        return TYPE_ITEM;
    }

    private boolean isPositionHeader(int position) {
        return position == 0;
    }

}



Now if you run the app this is what you would see




As you can see the drawer is overlapping the Toolbar/ Action bar, If you are happy with this design and pattern then you can consider the project done, as this pattern is also one of the material design patterns used by many official Google apps and other apps as well, now if you want to make the status bar translucent and have your drawer slide under the status bar then you should follow along

Before we get to making the status bar translucent and having our drawer slide below it I must tell you the method you are going to see isnt exactly the right way to implement the above effect as if we want the drawer to slide below the status bar we have to make the status bar translucent and once we make it translucent we can not assign any color to the status bar. You would understand what I am talking about in just a minute

First let me tell you that the status bar translucent method is not available for pre kitkat devices, so we make two styles.xml files one for version 19 api (kitkat) and one for Version 21 api (Lollipop). so in all we have three styles.xml files.

we now add the following styles to both our styles.xml files i.e style for kitkat and lollipop
here is how the style.xml file look for both the files.


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar" >
        <item name="android:windowTranslucentStatus">true</item>
    </style>

</resources>

Now if you look at the app this is what you are going to see


As you can see we have got the translucent status bar but the toolbar got below it and if you add the android:fitSystemWindows="true"  tag in your activity_main.xml as a property to the root layout( DrawerLayout) file the toolbar will move down and adjust to the status bar but even if we get the toolbar down we won't be able to change the color of the status bar once it is set to translucent. now as i have earlier said this is not the exact method to do this, if you look at the stack overflow discussion here you could find that to achieve the above effect you have to use scrimInsetFrameLayout which i dont belive is really very complicated for this effect

So what I do is I have added a padding of 24dp to the tool_bar.xml and as I only want the padding to take effect on kitkat and lollipop devices I have made two dimens files with version api set to 19 and 21 for kitkat  and lollipop respectevely and for the pre lollipop devices I have set 0dp padding in the 3rd dimens file, then I have added the padding top to tool_bar.xml

so finally this is how tool_bar.xml looks
<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/ColorPrimary"
    android:theme="@style/ThemeOverlay.AppCompat.Dark"
    android:elevation="4dp"
    android:paddingTop="@dimen/tool_bar_top_padding"


    >

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



Now everything is done and set and if you open the app this is what you would get




Perfect it looks just the way wanted it to be, So that's how you make a Material design Navigation Drawer which has a Hamburger Toggle icons animating into arrow. If you liked this post please comment and share the post on your social networks.

EDIT: head over to Recycler View : Handling OnItemTouch For Navigation Drawer post if you want to learn how to handle the click events for navigation drawer.

Akash bangad

Computer Engineer from Maharashtra,India. Trying to make my way in the world of mobile development. Steve Jobs admirer and techy at heart.

190 comments:

  1. I ran into a problem. In MyAdapter.java, the following lines give me an error, specifically, the word "this" is underlined in red:

    public ViewHolder(View itemView,int ViewType) {
    super(itemView);
    itemView.setOnClickListener(this);

    As a result, I am unable to run the application. The LogCat gives me this output:

    Error:(43, 21) error: method setOnClickListener in class View cannot be applied to given types;
    required: OnClickListener
    found: ViewHolder
    reason: actual argument ViewHolder cannot be converted to OnClickListener by method invocation conversion

    Yet I have no idea what it means. If you could help me figure this out, that would be great.

    ReplyDelete
    Replies
    1. Hey Kevin,
      Thanks for your comment, The setOnClickListener shouldn't be there in the code. I have updated the code by removing the setOnClickListener. Hope so that this will solve your query

      PS - if you want to learn how to handle the clicks on the sliding drawers list items, I would come up with the tutorial for that soon.

      Delete
    2. Thanks for the reply! I think that was the only issue I came across so it'll probably build properly now. Thank you!

      Delete
    3. Android Chat Head Library
      Chat head is new feature which floats on screen instead of residing inside conventional application. This feature is very continent for multitasking as user can work and chat at the same time.
      Android Chat Head Library

      Delete
  2. Thank you for your awesome instruction. Can I ask, how to do overlapping drawer? My drawer is still under action bar (builded at android v4.4.2).

    And I'm really excited for your next post how to handle the clicks on the sliding drawers list items (from this recipe)! :-)

    ReplyDelete
    Replies
    1. Sorry for the late reply, I was busy with some work but I am back to blogging and as requested the post on handling clicks for navigation drawer is added, so please check that out, also if you have problem implementing the code send me a mail with more details I would like to help you out and finally I have started the mail list for this blog so if you would like to stay updated with this blog make sure you subscribe to the mail list.

      Delete
  3. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. Change your activity_main.xml => change RelativeLayout into android.support.v4.widget.DrawerLayout
      then a RelativeLayout with include toolbar and a textview

      Delete
    2. Thank you for your response. I did it like you wrote. Drawer is overlapping, but open/close doesn't work - it's still open and can't be closed. Any ideas, please? :-)

      Delete
    3. If you do everything right then the drawer should work just fine, still if you are facing any difficulties send me a mail with more details I would surely look through it.

      Delete
  4. And I'm really excited for your next post how to handle the clicks on the sliding drawers list items (from this recipe)! :-)


    me to

    great tutorial thank

    ReplyDelete
    Replies
    1. Added the post for handling clicks on sliding drawer, make sure to check it out, also please subscribe to the mailing list to receive updates from this blog right in your inbox

      Delete
  5. The navigation drawer is not overlapping the toolbar when opened.

    ReplyDelete
    Replies
    1. Make sure you add the drawer layout as the root layout, If you do everything right it would surely work. If you continue to face same problem send me a mail with more details and I would help you solve it.

      Delete
  6. How can I make the hamburger icon to spin and transform into the arrow? I have a navigation drawer implemented like yours but my hamburger changes instantaneously into the arrow when the drawer finishes to open and instantaneously back into hamburger when it finishes to close.

    ReplyDelete
    Replies
    1. Well, If you follow the tutorial then you should get the desired results, I can not think of any reason that would trigger such a behaviour, make sure you are not in battery saver mode of lollipop it chops of all the animations to save your battery. if you are not getting what you want feel free to shoot me a mail and ill help you with the code.

      Delete
  7. Hi, first off great tutorial. I just have one problem, and that is that the hamburger menu icon isn't showing up. I followed this tutorial first (http://www.android4devs.com/2014/12/how-to-make-material-design-app.html?showComment=1421694813961#c755545335591885555) and then built off that with this tutorial. Any ideas? I followed the directions to a T but no luck :(

    ReplyDelete
    Replies
    1. Also, in my activity_main.xml on this section "" I get an error: "Top level element is not completed".

      Delete
    2. If you have followed the tutorial then you should get the proper results anyways, to help you I would need to check out you code, so if you want you can mail me your project code and ill do the necessary changes and get back to you.
      cheers

      Delete
  8. This comment has been removed by the author.

    ReplyDelete
  9. if you use windowTranslucentStatus=true in Lollipop, you dont get the real colorPrimaryDark. The real way to get a navigation drawer over statusbar in Lollipop is using this: http://stackoverflow.com/a/27153313/3262021

    ReplyDelete
  10. Great tutorial! It's hard to find everything in one place.

    You might consider following google's design guide (http://www.google.com/design/spec/patterns/navigation-drawer.html) and update the item_row a little. Through a little tinkering it seems like the icon size is 24dp, and the height is 48dp as mentioned. Here is my implementation if it helps. http://ix.io/fXr

    ReplyDelete
  11. There is a typo. 'android:fitsSystemWindows="true" ' and not 'android:fitSystemWindows="true" '

    ReplyDelete
  12. First of all thanks for great tutorial ,but now I want to implement onClicklistener on item in list ,how to do that?

    ReplyDelete
  13. Hello! Thanks a lot for your work! Help me please!
    I have the error in this line:
    mLayoutManager = new LinearLayoutManager(this); // Creating a layout Manager
    android studios hint is: "LinearLayoutManager is abstract; cannot be instantiated" That i did wrong?

    ReplyDelete
  14. Hm, i made new clear project and step by step did all like in your article. It`s worked. My main project I did in Eclips, maybe yhat`ss why I had an error.

    ReplyDelete
  15. This comment has been removed by the author.

    ReplyDelete
  16. Great article, easy to follow.
    However the drawer is not overlapping my action bar (that is my goal) .... my min is SDK 14, any thoughts ?

    ReplyDelete
  17. More.
    1. "layout_gravity" does not work on my S4 (4.4.2), instead I have to use alignParentStart/End=true
    2. No way to close drawer. I set it on the right side (alignParentEnd), clicked on the drawer button, the app crashed with:
    java.lang.IllegalArgumentException: No drawer view found with gravity LEFT
    at android.support.v4.widget.DrawerLayout.openDrawer(DrawerLayout.java:1293)

    so obviously drawer is in CLOSED (!) state.
    3. onDrawerOpened/Closed methods were not called although comments reads: "code here will execute once the drawer is opened"
    4. totally confused about styles.xml vs style.xml !?

    ReplyDelete
  18. Excellent tutorial!!! But what do i do if i want the nav drawer to be accessible on slide left in any actiivity?

    ReplyDelete
  19. I have done the code as mentioned in steps in your blog but the drawer is getting open below the toolbar i.e not occupying full height of screen.
    Kindly let me know the reason to overcome this issue

    ReplyDelete
  20. How do you set the navigation drawer icon to NOT change into back arrow when item is selected from the drawer? Like in Google's apps (Gmail, AppStore etc)

    ReplyDelete
  21. Can you please give me style.xml, color.xml, string.xml, file. I'm beginner, I Can't figure out some values which you've use in above tutorial -Thank You

    ReplyDelete
  22. Why don't you post your full source code and make it downloadable.... It is hard to follow your tutorials

    ReplyDelete
  23. Hello, Nice tutorial. But then wwhen i open my drawer it kind of lags near the profile picture. it says frames skipped and so .. it also says too much work done on the main thread

    ReplyDelete
    Replies
    1. Hi, I encountered the same problem on my moto g (stock 5.1). Funny thing, the exact same build doesn't lag at all on older, lower res 320*480 Xperia mini pro (CyanogenMod 12.1). Maybe circleimageview cannot render big image properly? I tried replacing the profile picture with a small 48*48 png and it runs smoothly.

      Delete
  24. The Drawer is below of Tool Bar, please help me. Very nice tutorial, is the only error that I got. Thanks.

    ReplyDelete
  25. This is a nice tutorial but I have en issue, when I slide the navigation drawer open very slowly, it gets stuck after a few pixels. How can I fix that?

    ReplyDelete
    Replies
    1. Same problem for me. Did you solved it already?

      Delete
    2. This solution seems to be fix (feels more like a workaround):

      http://stackoverflow.com/questions/17896052/why-does-drawerlayout-sometimes-glitch-upon-opening

      Delete
  26. ffs this...

    STRUCTURE of activity_main.xml:

    DrawerLayout
    RelativeLayout
    Toolbar
    ReciclerView


    ReplyDelete
    Replies
    1. The Code is been updated, with the the proper activity_main.xml

      Delete
  27. Just one question: If we hold the click (for 4-5 seconds) our event won't get triggered. How can this issue be fixed?

    Thanks in advance.

    ReplyDelete
  28. Hi, Thanks for nice tutorial.

    Can we have this project as downloadable ?

    ReplyDelete
  29. This comment has been removed by the author.

    ReplyDelete
  30. Hey..Thanks for helping us.. but i need your favor. actually i want to set background in items when i click on particular item n also remove when i clicked another item..& i also want to implemnt navigationcallbacks & i can't able to do it.. plase help me out when you will get this msg.

    ReplyDelete
  31. Thank you very much for your contribution!! I learned a lot from this post and adopted the technique for my personal product (https://play.google.com/store/apps/details?id=com.gogocosmo.cosmoqiu.fire_sticker). I'm expecting more valuable tutorials here now or in the future^_^

    ReplyDelete
  32. Very nice tutorial man, thanks a lot

    ReplyDelete
  33. Great turorial,

    Can you upload you code so we can use all de resource file that your example app needs to comple.

    Thanks.

    ReplyDelete
  34. hello
    i want to know how to get rid of header ?
    tnx

    ReplyDelete
  35. setSupportActionBar in ActionBarActivity cannot be apply to (android,widget.toolbar)
    in this line setSupportActionBar(toolbar);

    ReplyDelete
    Replies
    1. ActionBarActivity is now deprecated... use AppCompatActivity instead...

      Delete
  36. this is really nice tut. but i want to know something like how can i bring some dp down to actionbar?

    ReplyDelete
  37. hey. very nice tutorial. Can you help me out with this please?
    I want to implement tabs slide view + the above navigation drawer.. exactly similar to existing google play.
    I have implemented the above navigation drawer. Now how to add tabbed view to my screen?? I have searched a lot, but not something what i am searching for.
    Thanks in advance

    ReplyDelete
    Replies
    1. follow material design playlist from "slidenerd" at youtube...

      Delete
  38. This comment has been removed by the author.

    ReplyDelete
  39. I just wanted to change the navigation drawer icon (or if I can change the color that would be great) I couldn't find a way to do that.
    although I searched a lot. please share the solution with me if you have
    Thanks

    ReplyDelete
  40. Hi, Thanks for sharing nice tutorial its great to introduce those concept, at the same time link for entire project should be awsome. Can you share me the project setup so that I can use it on and work on.

    ReplyDelete
  41. How to go from one fragment to another when user clicks on Drawer List Item?

    ReplyDelete
  42. I used this great example o start an app, i'm a complete newbie and this help a lot ..

    The question i have since i'm starting new activities for each menu item how i can keep the tool_bar with different titles and back/up arrow for the sub/children activities

    Thanks

    ReplyDelete
  43. This comment has been removed by the author.

    ReplyDelete
  44. This comment has been removed by the author.

    ReplyDelete
  45. This comment has been removed by the author.

    ReplyDelete
  46. Use this code in the if statement in MainActivity.Java if you want a different action (such as opening a new activity) to be performed depending on which item is clicked:

    if (recyclerView.getChildPosition(child) == 0) {
    // DO SOME ACTION
    }

    else if (recyclerView.getChildPosition(child) == 1) {
    // DO SOME ACTION
    }

    ReplyDelete
  47. I just followed your tutorial but I do get a weird looking appbar on lollipop Samsung devices. Can someone look at my StackOverflow question? http://stackoverflow.com/questions/29747194/strange-appbar-on-samsung-devices

    ReplyDelete
  48. Hi, I was checking my Drawer Menu on Lollipop and app icon is not showed, at least by default, as usual (besides hamburguer icon). Does anybody knows how to address this issue?

    ReplyDelete
  49. Great tut. How to implement an onClickListener?

    ReplyDelete
  50. please help me out...
    In MainActivity.java class
    R.string.openDrawer,R.string.closeDrawer is not working . It simply says can not resolve symbol. what should i do now ??

    ReplyDelete
    Replies
    1. their names are actually:
      R.string.navigation_drawer_open , R.string.navigation_drawer_close
      he just forgot to change them.

      Delete
  51. This comment has been removed by the author.

    ReplyDelete
  52. Actually my problem was not in R.string.navigation_drawer_open . It was in toolbar.
    it says incompatible types: Toolbar cannot be converted to int .
    please help me if anyone had the same problem ..

    ReplyDelete
  53. Problem solved Android studio automatically import the package
    import android.support.v4.app.ActionBarDrawerToggle
    instead of
    import android.support.v7.app.ActionBarDrawerToggle .

    ReplyDelete
    Replies
    1. Hi Vipin ,

      I don't get it .. I am getting the same problem here
      R.string.openDrawer & R.string.closeDrawer (can't resolve them)

      how did you fixed the issue ?

      Delete
  54. how can i put icons on the botton of the navigation drawer?

    ReplyDelete
  55. how to do this example in eclipse please any 1 can help...

    ReplyDelete
  56. Thanks for the nice tutorial. Can you please help with the query below: How can i show a navigation item as selected in navigation drawer, which is the default behavior of google's navigation drawer and got lost while customizing it.

    ReplyDelete
  57. Great tutorial, thanks, working fine for me

    ReplyDelete
  58. Great tutorial..I want to set the background for footer view.If I set back ground for RecyclerView then the background appears on complete navigation drawer.If i set the background for item_row.xml then it appears only on the item of the list in footer.But I want to set the background for complete footer just like it has been set for the header in the tutorial.How can i do that?

    ReplyDelete
  59. Great tutorial, but it has a bug: in landscape mode the toolbar does not take the planned height of the material design (40dp) but maintains that the portrait mode (48DP), while the title text respects the smaller size and then loses' alignment with the icons on the toolbar. how do I fix? thanks

    ReplyDelete
    Replies
    1. I had a similar problem on my tablet device where the toolbar height is supposed to increase to 56dp, but the icons were not aligned properly. I fixed it by setting the layout_height on the toolbar to 56dp+24dp for tablet devices (where 24dp is the value of the top padding). You could probably do something similar for landscape.

      Delete
  60. For god's sake please dont throw half baked products It is asking ColorPrimary tool_bar.xml!When you gve an example to try, how could you think us as all-in-one?

    ReplyDelete
  61. Can i use this code in Eclipse IDE

    ReplyDelete
  62. How i get the library for circular image for eclipse juno

    ReplyDelete
  63. I'm getting an error: "cannot resolve symbol R" in MyAdapter.java

    I've tried cleaning/rebuilding project and gradle sync. However the problem still persists. Can you help me with this?

    ReplyDelete
  64. Please resolve this error,

    Error:(72, 79) error: cannot find symbol variable navigation_drawer_open
    Error:(72, 113) error: cannot find symbol variable navigation_drawer_close

    ReplyDelete
    Replies
    1. This comment has been removed by the author.

      Delete
    2. your missing

      <(\)string name="navigation_drawer_open">Open navigation drawer<(\)/string>
      <(\)string name="navigation_drawer_close">Close navigation drawer<(\)/string>

      in your strings.xml file. This is located res>values>strings.xml

      Note: This is without the four "(\)"s

      Delete
  65. What is the background image size (dimensions) you applied?

    android:background="@drawable/background_poly"

    Width and Height.

    ReplyDelete
  66. Android team has released new support library with all its new components in it. NavigationView is one of them to support lollipop style navigation drawer. As the library is new there is lack of how to documentation on it. If you could retrofit your block adapting the new support library. It will help the community. Refer this links for more details...

    https://developer.android.com/tools/support-library/features.html#design

    http://android-developers.blogspot.in/2015/05/android-design-support-library.html

    ReplyDelete
  67. Thanks for the Amazing tutorial. I have followed every step of yours but the as I run it on emulator it crashes. I am building the Navigation bar separately from ym app so that it doesn't cause errors in my running application. But as I run it, it gives the error: "Unfortunately, Testing_sidebar has stopped"

    ReplyDelete
  68. Hi, thank you for the tutorial it's very helpful!
    I have seen so many people asking how can they implement the click listener to a drawer item, so let me tell you.
    First of all implement the "OnClickListener" in your ViewHolder and set the "OnClickListener" to the view you send to the constructor ("itemView" in this tutorial). In the ViewHolder too, create a method which you are going to call from the view clicked.
    Now, in the Adapter "onBindViewHolder" method call the Holder method created in the step before.
    With this simple steps you are able to click the drawer items succesfully.

    ReplyDelete
  69. How can I set the image in the header imageview dynamically. I have the facebook integration in my app and I want to retrieve the profile picture of user and set in to navigation drawer header as you are setting yours statically. How can I set it dynamically ?

    ReplyDelete
  70. Haloo.My app crashes immediately I launch. I get the error on in the onCreateViewHolder on the if else statement.Please help

    ReplyDelete
  71. Can you state the best way I can implement the navigation drawer in every Activity of my application? I know I could extend the DrawerActivity in every Activity, but what if my other Activities extends some other classes? Like ListFragment etc etc?

    ReplyDelete
  72. Can you state the best way I can implement the navigation drawer in every Activity of my application? I know I could extend the DrawerActivity in every Activity, but what if my other Activities extends some other classes? Like ListFragment etc etc?

    ReplyDelete
  73. Great tutorial!! Source code on Github would be highly appreciated !!

    ReplyDelete
  74. This comment has been removed by the author.

    ReplyDelete
  75. Hello, thanks for your amazing tutorial. Yesterday i have tried your material toolbar tutorial and it works. But, i have a problem in this tutorial especially in MyAdapter.java class in line View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.header,parent,false);//error
    on method public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType). I hope you can give me a solution about my problem. I'm very interesting about material design android. Thank you very much.

    ReplyDelete
    Replies
    1. same problem if u solved this help me

      Delete
  76. Hey, I've been able to implement the NavDrawer. The problem is I don't use an ActionBar in my app so i just open the NavDrawer manually upon a particular button click. The drawer opens but i'm not able to select any item from it. It just closes as soon as i touch on it anywhere. I just use method Drawer.openDrawer to open it.

    Any help would be appreciated, Thanks!

    ReplyDelete
  77. Hi!

    Thank you for very nice tutorial.
    My question is: Why do you prefer to use RecyclerView instead of ListView in NavigationDrawer ?
    According to google: RecyclerView is
    1) a container for displaying large data sets that can be scrolled very efficiently by maintaining a limited number of views.
    2) Uses internally a layout manager. A layout manager positions item views inside a RecyclerView and determines when to reuse item views that are no longer visible to the user. To reuse (or recycle) a view, a layout manager may ask the adapter to replace the contents of the view with a different element from the dataset.

    Because you are using here very small dataset (header + a short list) and all items are still visible to user, you cannot benefit from recycler view "features" in 1) & 2).
    Even Google in their official docs: http://developer.android.com/training/implementing-navigation/nav-drawer.html#DrawerLayout used ListView.

    It this case it seems that RecyclerView makes things only complicated (handle item click from Activity, add separator, ...)

    Thank you for your answer.

    ReplyDelete
  78. I am unable to style the menu items in this drawer using styles.xml as I normally would with a ListView. Is this not possible using this method? (ex. pressed, activated, selected, etc. states)

    ReplyDelete
  79. I am unable to style the menu items in this drawer using styles.xml as I normally would with a ListView. Is this not possible using this method? (ex. pressed, activated, selected, etc. states)

    ReplyDelete
  80. This comment has been removed by the author.

    ReplyDelete
  81. i am getting an error like d by: java.lang.NullPointerException: Attempt to invoke virtual method 'java.lang.CharSequence android.support.v7.widget.Toolbar.getTitle()' on a null object reference..
    pleasse help me to get rid of this error

    ReplyDelete
  82. I have followed every step of yours but the as I run it on emulator it crashes. I am building the Navigation bar separately from ym app so that it doesn't cause errors in my running application. But as I run it, it gives the error: "Unfortunately, Testing_sidebar has stopped".. and my R.java file has been missing.

    ReplyDelete
  83. how to add click listener to select fragments

    ReplyDelete
  84. Great tutorial! I am getting problem in adding import android.support.v7.widget.Toolbar.I dont know how to add it.Could you please help me?

    ReplyDelete
  85. I am finding error in opening and closing of drawer
    Error is in mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){
    error : cannot find symbol variable openDrawer

    ReplyDelete
  86. The same problem as Maryam Jamil's while running/compiling code:

    Error:(70, 79) error: cannot find symbol variable openDrawer
    Error:(70, 99) error: cannot find symbol variable closeDrawer

    ReplyDelete
    Replies
    1. just replaced it with "app_name" for a moment and now it works. Thanks a lot for the tutorial/

      Delete
  87. Am I the only one who things your are to erratic with your naming decisions? Pick a convention and just stick to it.

    ReplyDelete
  88. I'm generally patient but this article was full of little annoyances I had to work out on my own..

    ReplyDelete
  89. hello i had following error:-

    - closeDrawer cannot be resolved to a
    variable
    - openDrawer cannot be resolved to a
    variable
    - openDrawer cannot be resolved or is
    not a field
    - closeDrawer cannot be resolved to a
    variable

    please help me to proceed my work...Thanks

    ReplyDelete
  90. How do item icon is full color?

    ReplyDelete
  91. You can not categorize the items in navigation drawer (separating by lines ) by adding navigation drawer this way(by following above tutorial).

    ReplyDelete
  92. mate, I run into more than 40 problems with your code.
    Error:(30, 5) error: cannot find symbol class RecyclerView
    Error:(31, 17) error: package RecyclerView does not exist
    Error:(32, 17) error: package RecyclerView does not exist
    Error:(54, 26) error: cannot find symbol class RecyclerView
    Error:(64, 30) error: cannot find symbol class LinearLayoutManager
    Error:(132, 5) error: method does not override or implement a method from a supertype

    can you provide a better text? and perhaps specify which kind of starting layout do you want?

    ReplyDelete
  93. hello sir can you implement the code of navigation drawer without recycler view

    ReplyDelete
  94. i think you shoud change method getview,
    http://www.chuanroi.net/

    ReplyDelete
  95. i think you shoud change method getview,
    http://www.chuanroi.net/

    ReplyDelete
  96. Why does this crash on Jellybean ? It works on all platforms from Froyo to Marshmallow but except Jellybean !! PLZ HELP !

    ReplyDelete
  97. Sir, please make the source code downloadable?

    ReplyDelete
  98. RecyclerView is not displaying on full screen height

    ReplyDelete
  99. How to set shadow to navigation drawer???

    ReplyDelete
  100. Quick question: what is the image you used for the background of your header called and where can I find it? I'm assuming its creative commons because I've seen it in a few places, but my own searches have been fruitless. Thank you for your tutorial btw, it was very helpful!

    ReplyDelete
    Replies
    1. https://www.google.com/search?q=background+poly&espv=2&biw=1920&bih=1017&source=lnms&tbm=isch&sa=X&ved=0CAYQ_AUoAWoVChMI2I201JDLyAIVxgqOCh33mQ2l

      Delete
  101. This comment has been removed by the author.

    ReplyDelete
  102. Hey Akash, do you know how to add a drop down in one of the list view options?

    ReplyDelete
  103. I need Help with..... This Error ---Couldn't load memtrack module (No such file or directory)

    and This Errror E/RecyclerView﹕ No layout manager attached; skipping layout

    ReplyDelete
  104. Good Post! Thank you so much for sharing this pretty post, it was so good to read and useful to improve my knowledge as updated one, keep blogging…
    Regards,
    SAP training in chennai

    ReplyDelete
  105. This comment has been removed by the author.

    ReplyDelete
    Replies
    1. could u provide a downloadable source code. that would be a great help....

      Delete
  106. Hi Admin,
    I like your writing style, it was very clear to understanding the concept well; I hope you ll keep your blog as updated.
    Regards,
    Angularjs training in chennai|Angularjs training chennai|Angularjs course in chennai|Angularjs training center in Chennai

    ReplyDelete
  107. anyone having troubles in copying codes or just me :(

    ReplyDelete
  108. Thanks Akash , you explained very well about navigation drawer . It is very helpful and it ran in first attempt correctly.Best of luck

    ReplyDelete
  109. can anyone tell me which part of this code that makes the navigation drawer slides from left to right?

    ReplyDelete
  110. can anyone tell me which part of this code that makes the navigation drawer slides from left to right?

    ReplyDelete
  111. Updating with the current trend is strictly advisable and the content furnished here also states the same. Thanks for sharing this wonderful and worth able article in here. The way to expressed is simply awesome. Keep doing this job. Thanks :)

    JAVA J2EE Training Institutes in Chennai | JAVA Training | JAVA Course in Chennai | software testing training in chennai

    ReplyDelete
  112. Hi, nice tutorial but I don't like using Recycler View... Is there another way to create menu items with icons and texts clickable without using it?

    ReplyDelete
  113. Hi, Can we create tabs and Navigation Drawer in a single row?

    ReplyDelete





  114. here where is tool_bar in layout file??????

    ReplyDelete
  115. thx a lot for this amazing tutorial, so inspiring

    ReplyDelete
  116. This tutorial was one of the easiest and the best to understand! way to go,thank u so much :)

    ReplyDelete
  117. Great tutorial!! Source code on Github would be highly appreciated !! | Android App Development

    ReplyDelete
  118. how set click listener to the circular image please reply soon very urgent.

    ReplyDelete
  119. This comment has been removed by the author.

    ReplyDelete
  120. It's Awesome.. so easy and helpful
    But how I can add Counter for mail and event in navigation drawer ?

    ReplyDelete
  121. night,
    thanks for the tutorial. please advice and criticism on my first application
    https://drive.google.com/file/d/0B3eiYbiyWsShbEg4SWRxMzdnU2s/view?usp=sharing
    thank you

    ReplyDelete
  122. What a great tutorial, it works as a charm ^___^
    really happy to visit ur blog (Y)

    ReplyDelete
  123. How to highlight the current opened fragment in Recyclerview

    ReplyDelete
  124. Hello i like how you guide one in the whole process. I have errors when under recyclerView in both MyAdapter and MainActivity classes. Please give me a reply on how to solve it

    ReplyDelete
  125. Great tutorial...so easy and helpful .

    ReplyDelete
  126. i got the error here:



    it says no resources found that given name

    ReplyDelete
  127. This is the game so players feel very fierce , adventurous . You try to join and play this game , you will feel great like.
    age of war | tank trouble 2 |earn to die
    gun mayhem | gun mayhem 2
    slitherio | slither.io | slither io
    can your pet | Red Ball | | duck life

    ReplyDelete
  128. good tutorial ,but where is the update i want to make click on items f recycle view

    ReplyDelete
  129. why when i click on image in header app crush

    ReplyDelete
  130. This comment has been removed by the author.

    ReplyDelete
  131. Hi.
    Drawer Layout is an error.
    could you pls help me define it

    ReplyDelete
  132. How to open new activity on click event of navigation header and navigation drawer work correct if any item selected of navigaton view from new header activity

    ReplyDelete
  133. I am so happy to read this. This is the kind of manual that needs to be given and not the random misinformation that's at the other blogs.
    ColdFusion Assignment Help

    ReplyDelete
  134. This comment has been removed by the author.

    ReplyDelete
  135. Nice Article If You Have Shared source code it would have been very useful as Few Files are missing like style.xml ,dimin.xml and other

    ReplyDelete
  136. All Working fine but when i open navigation drawer it getting Strucked and opening any solution ???? Please Do Mail me on raju.shiva14@gmail.com

    ReplyDelete
  137. hi any changes in manifest file?

    ReplyDelete
  138. The share your really gives us excitement. Thanks for your sharing. If you feel tired at work or study try to participate in our games to bring the most exciting feeling. Thank you!
    hotmail sign in | red ball 1

    ReplyDelete
  139. The blog or and best that is extremely useful to keep I can share the ideas of the future as this is really what I was looking for, I am very comfortable and pleased to come here. Thank you very much.
    animal jam | five nights at freddy's | hotmail login

    ReplyDelete
  140. This comment has been removed by the author.

    ReplyDelete
  141. In your blog I was happy to see your article, better than last time, and have made great progress, I am very pleased. I am looking forward to your article will become better and better.
    hotmail login | red ball | 192.168.1.1

    ReplyDelete
  142. how to change navigation drawer header email text using java code?

    ReplyDelete
  143. great article, I was very impressed about it, wish you would have stayed next share

    Facebook Lite | Baixar Facebook | whatsapp baixar
    Score Hero

    ReplyDelete
  144. Very Nice Blog I like the way you explained these things.
    Indias Fastest Local Search Engine
    CALL360
    Indias Leading Local Business Directory

    ReplyDelete
  145. GREEN WOMEN HOSTELGreen Women hostel is one of the leading Ladies hostel in Adyar and we serving an excellent service to Staying people, We create a home atmosphere, it is the best place for Working WomenOur hostel Surrounded around bus depot, hospital, atm, bank, medical Shop & 24 hours Security Facility

    ReplyDelete