Creating Android Sliding Sidebar (Hamburger) Menu with Navigation Drawer Icon

By now most of us are familiar with Navigation Drawers as they’ve been in use by Facebook, Gmail, Google Play Music, Google Play Music and tons of others apps. It’s that sliding panel that comes out onto the screen when you swipe a finger from the left edge of the screen (or sometimes right edge) or tap on the 3 bar button (sometimes called hamburger icon) in the Action Bar. If still confused then check out the design guide and you’ll know what I’m referring to. The design guide will also tell you when to use it and when not to use it.

In this article I’ll go through how to create a navigation drawer (also referred to as sidebar menu, slide-out menu, sliding menu, hamburger menu, basements, etc.) for your own apps using the DrawerLayout APIs in the support library. But before getting into how to create a navigation (hamburger) drawer, you should not only go through the design guide but also read a couple of articles on how you might be making a wrong decision by using a hamburger menu and you could possibly resort to other methods to avoid it:

What's the one thing every developer wants? More screens! Enhance your coding experience with an external monitor to increase screen real estate.

That’s a lot to read (but won’t take much time) and too much negativity around navigation drawers. But if you think you’re fixed on using it because it does make sense in several cases, then let’s head towards creating one on Android. Here’s a screenshot of the navigation drawer we’ll create (with an Action Bar).

android navigation drawer

Simple and Clean!

DrawerLayout ViewGroup in Your Layout

We’ll first code our layout in res/layout/activity_main.xml. In order to build a drawer, we’ll have to use a DrawerLayout as the root view of our layout which’ll contain two child ViewGroups where one of them will represent the main content, whereas the other will contain the contents of the navigation drawer.


    <!-- The main content view -->
        android:layout_height="match_parent" />

    <!-- The navigation drawer -->

        <!-- Profile Box -->

            android:padding="8dp" >

                android:layout_marginTop="15dp" />

                android:orientation="vertical" >

                    android:textStyle="bold" />

                    android:text="View Profile"
                    android:textSize="12sp" />

        <!-- List of Actions (pages) -->
            android:background="#ffffffff" />



As you can see, we’ve our DrawerLayout root view and then its first child is a RelativeLayout that represents the main content UI whereas the second child represents the navigation drawer. The navigation drawer first contains a box to represent the profile details followed by a ListView that’ll display a list of different sections that the user can visit (Home, Preferences, About).

The ViewGroup representing the main content UI should be the first child inside the DrawerLayout as the ordering in XML defines the z-index and the drawer should overlay the content, not the other way round.

The XML code is enough to initialize a functional drawer. You can test your app in the emulator or device to start swiping your finger from the left to draw the hamburger menu. However, we’ve some more work to do like initializing the list and adding onclick events on the list items.

Populating the Drawer List

This is the first step, we’ll initialize the ListView inside the Drawer with several options. Each list option will be represented by a custom NavItem class object. So create this inner class (of the MainActivity):

class NavItem {
    String mTitle;
    String mSubtitle;
    int mIcon;

    public NavItem(String title, String subtitle, int icon) {
        mTitle = title;
        mSubtitle = subtitle;
        mIcon = icon;

Next we need another inner class that’ll be a simple BaseAdapter implementation that we’ll bind to the ListView for the sake of population:

class DrawerListAdapter extends BaseAdapter {

    Context mContext;
    ArrayList<NavItem> mNavItems;

    public DrawerListAdapter(Context context, ArrayList<NavItem> navItems) {
        mContext = context;
        mNavItems = navItems;

    public int getCount() {
        return mNavItems.size();

    public Object getItem(int position) {
        return mNavItems.get(position);

    public long getItemId(int position) {
        return 0;

    public View getView(int position, View convertView, ViewGroup parent) {
        View view;

        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            view = inflater.inflate(R.layout.drawer_item, null);
        else {
            view = convertView;

        TextView titleView = (TextView) view.findViewById(;
        TextView subtitleView = (TextView) view.findViewById(;
        ImageView iconView = (ImageView) view.findViewById(;

        titleView.setText( mNavItems.get(position).mTitle );
        subtitleView.setText( mNavItems.get(position).mSubtitle );

        return view;

We inflated R.layout.drawer_item, so let’s create res/layout/drawer_item.xml now:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android=""


        android:text="Line 1"
        android:layout_toEndOf="@+id/icon" />

    <TextView android:id="@+id/subTitle"
        android:text="Line 2"
        android:layout_alignParentEnd="true" />


Now, we’ll set the adapter for the ListView inside onCreate() of our MainActivity:

private static String TAG = MainActivity.class.getSimpleName();

ListView mDrawerList;
RelativeLayout mDrawerPane;
private ActionBarDrawerToggle mDrawerToggle;
private DrawerLayout mDrawerLayout;

ArrayList<NavItem> mNavItems = new ArrayList<NavItem>();

protected void onCreate(Bundle savedInstanceState) {

    mNavItems.add(new NavItem("Home", "Meetup destination", R.drawable.ic_action_home));
    mNavItems.add(new NavItem("Preferences", "Change your preferences", R.drawable.ic_action_settings));
    mNavItems.add(new NavItem("About", "Get to know about us", R.drawable.ic_action_about));

    // DrawerLayout
    mDrawerLayout = (DrawerLayout) findViewById(;

    // Populate the Navigtion Drawer with options
    mDrawerPane = (RelativeLayout) findViewById(;
    mDrawerList = (ListView) findViewById(;
    DrawerListAdapter adapter = new DrawerListAdapter(this, mNavItems);

    // Drawer Item click listeners
    mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

Our ListView will be populated now so you should see it in the navigation drawer but it’s time to write code for what will happen once a list item is clicked, which will be defined by the selectItemFromDrawer() Activity method which is what we called inside the onItemClick() method of the OnItemClickListener interface.

So when a list item is clicked, we could do several things. Since they’re different sections, we could just open different Activities using intents, insert a different Fragment for every list item into the main content view or even show dialogs. In this case we’ll keep it simple by creating a fragment called PreferencesFragment and inserting it whenever an option is selected. Although you might want to create one fragment for each option and based on the position of the clicked item, insert its respective fragement. Let’s get into some code now.

* Called when a particular item from the navigation drawer
* is selected.
* */
private void selectItemFromDrawer(int position) {
    Fragment fragment = new PreferencesFragment();

    FragmentManager fragmentManager = getFragmentManager();
            .replace(, fragment)

    mDrawerList.setItemChecked(position, true);

    // Close the drawer

This is how looks like:

public class PreferencesFragment extends Fragment {

    public PreferencesFragment() {
        // Required empty public constructor

    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_preferences, container, false);


and here’s the res/layout/fragment_preferences.xml:

<FrameLayout xmlns:android=""
    xmlns:tools="" android:layout_width="match_parent"
    android:layout_height="match_parent" tools:context="com.looper.loop.PreferencesFragment">

    <!-- TODO: Update blank fragment layout -->
    <TextView android:layout_width="match_parent" android:layout_height="match_parent"
        android:text="@string/hello_blank_fragment" />


It’s time to test your app in the emulator or your device itself. You’ll see a nice navigation drawer when you swipe right from the left edge with the profile box and the list in which you can select various options which’ll reflect in the action bar title because of this piece of code inside selectItemFromDrawer():


Observe Open/Close Events of the Drawer

You can listen for the drawer’s open and close events by implementing DrawerLayout.DrawerListener whose onDrawerOpened() and onDrawerClosed() will be called. But if you’re making use of the action bar, then extending ActionBarDrawerToggle is a better idea. The ActionBarDrawerToggle implements DrawerLayout.DrawerListener, so you’ll have access to those callbacks but apart from that it also makes sure that the state of both the action bar icon (we’ll see how to add that in a bit) and the drawer is synced. Let’s see some code now.

mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
    public void onDrawerOpened(View drawerView) {


    public void onDrawerClosed(View drawerView) {
        Log.d(TAG, "onDrawerClosed: " + getTitle());



The four arguments passed to the ActionBarDrawerToggle constructor are:

  • this – Activity object containing the drawer with an ActionBar.
  • mDrawerLayout – The DrawerLayout to link to the Activity’s ActionBar.
  • R.string.drawer_open – String resource to describe the “open drawer” action for accessibility purpose.
  • R.string.drawer_close – String resource to describe the “close drawer” action for accessibility purpose.

There’s another version of this constructor that you should use when not using an ActionBar but a ToolBar.

You’ll notice in the callbacks we called invalidateOptionsMenu(). This method declares that the option menu has changed and hence should be recreated invoking onPrepareOptionsMenu(). So basically you might want to override onPrepareOptionsMenu() to get rid of options from your overflow menu that are irrelevant to your navigation drawer.

// Called when invalidateOptionsMenu() is invoked
public boolean onPrepareOptionsMenu(Menu menu) {
    // If the nav drawer is open, hide action items related to the content view
    boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
    return super.onPrepareOptionsMenu(menu);

Showing Up the Hamburger Menu Icon/Indicator

According to the design guidelines, apart from the touch gesture, when the drawer is closed the user should be able to open it by touching the navigation drawer indicator (those 3 lines) in the action bar. So now we’ll see how to display that special icon.

First, add this piece of code inside onCreate():

// More info:

This piece of code will start showing up an arrow which is generally used for “up” (ancestral) navigation. Now when the user taps on this, onOptionsItemSelected() will be called where you can delegate the event to the ActionBarDrawerToggle.

public boolean onOptionsItemSelected(MenuItem item) {
    // Pass the event to ActionBarDrawerToggle
    // If it returns true, then it has handled
    // the nav drawer indicator touch event
    if (mDrawerToggle.onOptionsItemSelected(item)) {
      return true;
    // Handle your other action bar items...

    return super.onOptionsItemSelected(item);

Now you’ll see the back arrow on which you can tap to open/close the drawer. But it won’t change to the 3 bar indicator icon when the drawer is closed. So in order to do that we’ve to override the onPostCreate() method of the Activity where we’ll call the syncState() method of the ActionBarDrawerToggle. This method syncs the state of the indicator with the drawer. So when the drawer is closed it’ll show the correct indicator (indicating tap to open) while when the drawer is open it’ll show the back arrow indicator (indicating tap to close).

protected void onPostCreate(Bundle savedInstanceState) {

With that, its time to test your app that is baked with a navigation drawer now.


So we went through how to use the DrawerLayout ViewGroup to create a navigation drawer and then populate that with a list of navigation options. Then we bounded click events to the list items that would replace the main content UI with a particular fragment. We also learnt how to listen to close/open events and show a navigation drawer indicator while using an action bar. You can also definitely make use of a Toolbar in place of an action bar and bind that to ActionBarDrawerToggle.

I don’t think by default the DrawerLayout supports sliding over the action bar which is what the material design guideline specify. So doing that might be a good exercise for you along with using custom images for the drawer icon/indicator in the action bar. If you give any of them a shot, then feel free to share your code in the comments section below!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download

Author: Rishabh

Rishabh is a full stack web and mobile developer from India. Follow me on Twitter.

76 thoughts on “Creating Android Sliding Sidebar (Hamburger) Menu with Navigation Drawer Icon”

  1. Hi, i was trying to implement your solution but i got an error on this line “view = inflater.inflate(R.layout.drawer_item, null);”. Cannot resolve R.layout.drawer_item

    Do you have any idea?, by the way pretty good article!!

    1. Hey Luis,

      Thanks for pointing that out. I’ve added the code for res/layout/drawer_item.xml. Just create that file and shove in the code and you’ll be good to go 🙂


    2. Hi Rishabh, I have tried implementing your code but for some reason I can’t select items on teh list. After the “mDrawerList.setItemChecked(position, true);” the item on the list is still unselected. I have to do something in themes or similiar? Thanks in advance

    3. In this line of code :-
      view = inflater.inflate(R.layout.drawer_item, null);

      In place of “null”, place the menu parameter of the overriden method “public boolean onCreateOptionsMenu(Menu menuVariable)”

      Example :-
      public boolean onCreateOptionsMenu(Menu menu) {
      getMenuInflater().inflate(, menu);
      return super.onCreateOptionsMenu(menu);

  2. Hi,i’ve got this error when i try to execute…
    java.lang.ClassCastException: android.widget.RelativeLayout$LayoutParams cannot be cast to$LayoutParams
    How can i solve?
    Thanks 🙂

    1. Ok solved…i ‘ve done a mistake!
      I’ve put mDrawerList instead of mDrawerPane …now it works 🙂 …maybe u have to correct ur code 🙂
      How ever thanks for ur example!
      public boolean onPrepareOptionsMenu(Menu menu) {
      // If the nav drawer is open, hide action items related to the content view
      boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
      return super.onPrepareOptionsMenu(menu);

      1. Can you please tell me, in the line

        what is “action_settings”, my project is not recognizing it.
        Please Help.

  3. There is another thing that is incorrect
    mDrawerToggle miss a parameter,the icon from resource.drawable…now is complete 🙂
    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.abc_ic_go, R.string.hello_world, R.string.app_name) {…}

    1. Pastebin your code and let me know where exactly do you get the NullPointer Exception ? If you follow the article step by step you probably shouldn’t get that Exception.

  4. Hi, in the last part of my MainActivity, i add the code as you describe in the tutorial, but i get this error: Error:(154, 70) error: incompatible types: PreferencesFragment cannot be converted to Fragment in the line

    Line: fragmentManager.beginTransaction().replace(, fragment).commit();

    Can you please tell me if you know how to fix?


    1. Hi,

      Are you sure you created a PreferencesFragment class that extends Fragment ? If yes then I’m unable to understand why that error would be thrown. Maybe try StackOverflow and see if someone can help you out.

      Also note you could use multiple fragments instead of just one PreferencesFragment for different items in the list. I used only once just for the sake of simplicity as my main objective is to show how to build the navigation drawer. Also based on the position you could set some Bundle data/arguments and then set layouts accordingly in the Fragment’s onCreateView method.

      1. I had this problem too and the soloution is using: + getSupportFragmentManager fragmentManager = getSupportFragmentManager();
        .replace(, new PreferencesFragment()).commit();

  5. Hey . Thank u for the guide it was useful
    There is a very one thing that I wanna know
    how is it possible to open the sliding menu by tapping the menu button on the phone?
    would u pls help me with it?
    thnx in advance

  6. hey, i want to a little discuss wiht you. i follow your tutorial.
    i adding some component in activity_main. why component in activity)main visible when i show fagment activity ?
    thanks before, and sorry for my bad englis 😀

    1. The article has the source code separated in logical bits for the sake of explanation. If you follow the steps you’ll end up building the source code yourself.

  7. Hey thanks for this amazing tutorial. Keep up the good work please 🙂
    One question, I was doing fine with the xml and the looks of the Slider Navigation. the app ran perfectly well.
    but when i was done with all the codes and run it in the emulator, it Force Close for no logical reason. I check the code several times and nothing was wrong.
    what do you think?
    I’m using android 4.3 for target and compile & android 4 for min sdk.
    Also, when I use fragment, it shows these two packages to me and wants me to choose one to import:
    which one should I choose? both for MainActivity and FragmentPreferences? maybe this will solve my problem
    Thanks for all the effort.

    1. iirc, instantiating ActionBarDrawerToggle will automatically show up the navigation drawer 3 bar icon. It could also be a theme-related thing though. I am using Theme.AppCompat.Light.DarkActionBa. If your theme is different and the icon doesn’t show up, do let us know the solution if you’re able to find it.

  8. i dont understand this mdrawertoggle part.will u please explain it .where do we need to write it and how to extend actionbartoggle when already activity class has been extended

    1. mDrawerToggle can go inside your Activity’s onCreate() method. I’ve explained it in the article as well as linked to relevant docs. Also you don’t make your Activity extend ActionBarDrawerToggle – that’s not what the code suggests.

  9. i tried your code it is working but not able to get back icon after drawer open,on the place of 3 bar.any solution.

  10. Where do I have to add this:

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
    public void onDrawerOpened(View drawerView) {


    public void onDrawerClosed(View drawerView) {
    Log.d(TAG, “onDrawerClosed: ” + getTitle());



  11. I am Using Fragment Activities(extend my main activity from fragment-activity) in my project so didn’t worked for me..please any have any solution for this ??

  12. Problem in Home Button.
    Home and Back button not working…

    When Drawer is open then Action bar should be behind drawer , mine is above..
    please reply

    1. @Override
      public void onBackPressed() {
      DrawerLayout drawer = (DrawerLayout) findViewById(;
      if (drawer.isDrawerOpen(GravityCompat.START)) {
      } else {
      if (getResources().getString(“2”)) {

  13. public boolean onPrepareOptionsMenu(Menu menu) { // If the nav drawer is open, hide action items related to the content view boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList); menu.findItem(!drawerOpen); return super.onPrepareOptionsMenu(menu); }
    Where this action_search is defined !

    1. That was an example stating how you might change the overflow menu options when the drawer is opened/closed. The is a MenuItem which would be defined in your Menu XML file.

      1. please reply to my comments the last one please. do it as soon as possible i am stuck in here please do help me out. how to open new fragments for each sliding menu. a separate page should be opened for each slides. for example for about slide a about page fragment, for home slide a home page fragment. Like a new activity for each of the slides u have designed. there are 3 slides in your illustration home, about and preferences. i need to know how to open a separate page for home, a separate page for about and a separate page for preferences.. please help me out as soon as possible.. please

  14. hello..
    I implement the code.. but where i add these parameter R.string.drawer_open & R.string.drawer_close

    please reply
    Thanks in advance

  15. Every Slides for example home,preferences and about opens a single layout called PreferencesFragment(). What will be the code to open separate pages for home, separate page for preference and separate page for about .. help needed desperately

  16. What if i need to fetch webdata using json and display it when navigation slider is clicked? any ideas? codes?

  17. getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    is not support for my code. appcompat v7 is added but its not get recognized here. when i try to add it as a librery my R file got deleted automatically. Is it work properly in v4?

    Thanks for the code this was very helpful. Reply pls

  18. Where can we download the source code?
    I ask this because, for example, the icons are where?
    It’s better to have the code to follow it offline.

  19. Hi, in my code it is showing error in this line menu.findItem( like cannot resolve symbol action_search.Plz give me the solution

  20. hi brother, my slide menu are finished, but Menu bar not display, how to fix this, please help me. thank you. and where can I download this

  21. 1-what do I have to import in the java classes?
    2-is there any downloadable file with the sources?
    3-how can I put intents?
    4-” Although you might want to create one fragment for each option and based on the position of the clicked item, insert its respective fragement” Although (…) what happens/what should I do?
    5-“Let’s get into some codes now” vs. “This is how looks like”. So which of these two is the correct one?

    I can’t even set the emulator

  22. is it possible to make a dynamic navitems? for example im fetching jsonarray/data from my web server which is category list, then i want to add those category inside the mnavitems.

    1. Yes of course, I’m basically passing mNavItems to the ListView’s adapter to populate the menu. You can feed in the json array/data into the same ArrayList and achieve what you want to.

  23. Hi. I followed your guide, but my side bar is 100% transparent and i can click buttons in main activity trhough this side bar. How to fix it? I don’t understand where I made a mistake

  24. There are some problems when implementing the ActionBarDrawerToggle.

    1) the drawerLayout is called drawer_layout

    2) What is not directly said -> you must replace the listener

    // Drawer Item click listeners
    mDrawerList.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    public void onItemClick(AdapterView parent, View view, int position, long id) {


    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {
    public void onDrawerOpened(View drawerView) {


    public void onDrawerClosed(View drawerView) {
    Log.d(TAG, “onDrawerClosed: ” + getTitle());



  25. Thank you for an amazing and easy-to-follow tutorial managed to do everything with great ease!
    But , I have a listview that populates with omdb-movies jsonobjects and it lays on one activity with everything so when I try to slide down with the list it seems that the custom drawerlayout is blocking the other layouts …

  26. Hi,
    Thanks for a very helpful post!
    I believe the activity_main.xml is missing a closing RelativeLayout tag around line 12.

  27. Hi All:

    Since you posted this tutorial, the ActionBarDrawerToggle has been deprecated and changed.

    The following line of code:

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout, R.string.drawer_open, R.string.drawer_close) {

    No longer is valid since the candidates for the new ActionBarDrawerToggle are:

    ActionBarToggle(@NotNull activity, drawerLayout, int drawerImageRes, int openDrawerContentDescRes, int closeDraserContentDescRes)

    To get the ActionBarDrawerToggle to properly function, a drawable object needs to added to the input params:

    mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_action_home, R.string.drawer_open, R.string.drawer_close)

    If anyone has any suggestions/comments about adding R.drawable.ic_action_home, let me know. Thanks!

    1. Hi All,

      For my implementation of this action bar, I want to update a subtitle of a particular drawer item. Does anyone have any suggestions for this? Would I need to make the DrawerListAdapter object a member of my activity class?

  28. Can we have a code of the working source code, it’s hard to compile a working project, especially being a beginner, when people jump all over the place. If I had the source code I’ll be able to follow along instead of trying to figure out why there are so many errors.

  29. getView() method is running in a loop for positions(0,1,2,0,1,2, like this), and i am getting a black activity. Please help asap. Thanks in advance. 🙂

  30. Good tutorial. Thanks. Let me clear one -> why do not you use ArrayAdapter instead of using BaseAdapter when creating custom listview.

  31. @Rishabh Hi Rishabh, thank you gor this great tutorial, I ahev followed this and understood the hamburger menu or navigation drawer or whatever.
    I have use this tutorial in file. And I am also using the Grid layout for my images and also this menu.
    But after implementing this tutorial I am unable to scroll the images in GridLayout.
    I tried to use ScrollView in activity_main.xml file, but during launching it say’s unfortunately stopped.
    Any help how could I fix this?

    1. To open an activity you can do this

      private void selectItemFromDrawer(int position)
      // if the user cliked on about section then :
      if(position == 2)
      // we well open the activity
      Intent intent = new Intent(getApplicationContext(),about.class);

  32. Your is set up to call one particular XML file (which prints ‘hello world!’)

    Can you advise/give me some pointers for working with individual fragments so that each item clicked in the list results in going to that fragment?

    This seems an important step – because after all, the nav drawer is all about navigation!

    Thanks for your help.

Leave a Reply

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