Android Navigation Drawer Example Step by Step

android navigation drawer horizontal open

Android Navigation drawer is now a standard when creating an Android app.

It gives a better user experience since the user can easily access more app functionality – on a small screen smartphone.

Personally, it is really fun to use since I just have to swipe a finger to use or access a view.

This post is a step by step guide on how to create a navigation drawer for your Android app.

android navigation drawer horizontal closed

android navigation drawer vertical opened

First, create a new project File > New > Android Application Project > “NavigationDrawerExample”

Android Navigation Drawer Example – Step by Step Guide

1. Change activity_main.xml to navigation drawer layout.

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/left_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />

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

2. Prepare MainActivity properties

private String[] mNavigationDrawerItemTitles;
private DrawerLayout mDrawerLayout;
private ListView mDrawerList;

3. res/values/strings.xml – put the drawer items array

<string-array name="navigation_drawer_items_array">
    <item>Create</item>
    <item>Read</item>
    <item>Help</item>
</string-array>

4. put inside MainActivity.java oncreate – initialize three properties.

mNavigationDrawerItemTitles= getResources().getStringArray(R.array.navigation_drawer_items_array);
mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerList = (ListView) findViewById(R.id.left_drawer);

5. create res/layouts/listview_item_row.xml

This is for list view inside navigation drawer. Right click res/layouts/ folder > New > File > Name it “listview_item_row.xml”

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"
    android:padding="10dp" >

    <ImageView
        android:id="@+id/imageViewIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:layout_alignParentTop="true"
        android:paddingRight="10dp" />

    <TextView
        android:id="@+id/textViewName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@+id/imageViewIcon"
        android:paddingRight="10dp"
        android:text="Folder name here."
        android:textAppearance="?android:attr/textAppearanceListItemSmall"
        android:textColor="#ffffff" />

</RelativeLayout>

6. create an object for drawer item ObjectDrawerItem.java

File > New > Class > Name it “ObjectDrawerItem”

public class ObjectDrawerItem {

    public int icon;
    public String name;

    // Constructor.
    public ObjectDrawerItem(int icon, String name) {

        this.icon = icon;
        this.name = name;
    }
}

7. put nav drawer item icons in res/drawable-hdpi/

I have:

ic_action_copy.png
ic_action_refresh.png
ic_action_share.png 

8. put inside oncreate – list the drawer items

ObjectDrawerItem[] drawerItem = new ObjectDrawerItem[3];

drawerItem[0] = new ObjectDrawerItem(R.drawable.ic_action_copy, "Create");
drawerItem[1] = new ObjectDrawerItem(R.drawable.ic_action_refresh, "Read");
drawerItem[2] = new ObjectDrawerItem(R.drawable.ic_action_share, "Help");

9. Create the custom adapter DrawerItemCustomAdapter.java

public class DrawerItemCustomAdapter extends ArrayAdapter<ObjectDrawerItem> {

    Context mContext;
    int layoutResourceId;
    ObjectDrawerItem data[] = null;

    public DrawerItemCustomAdapter(Context mContext, int layoutResourceId, ObjectDrawerItem[] data) {

        super(mContext, layoutResourceId, data);
        this.layoutResourceId = layoutResourceId;
        this.mContext = mContext;
        this.data = data;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        View listItem = convertView;

        LayoutInflater inflater = ((Activity) mContext).getLayoutInflater();
        listItem = inflater.inflate(layoutResourceId, parent, false);

        ImageView imageViewIcon = (ImageView) listItem.findViewById(R.id.imageViewIcon);
        TextView textViewName = (TextView) listItem.findViewById(R.id.textViewName);
       
        ObjectDrawerItem folder = data[position];

       
        imageViewIcon.setImageResource(folder.icon);
        textViewName.setText(folder.name);
       
        return listItem;
    }

}

10. Pass the list of drawer items to DrawerItemCustomAdapter

This is to create the adapter – inside MainActivity.java oncreate

DrawerItemCustomAdapter adapter = new DrawerItemCustomAdapter(this, R.layout.listview_item_row, drawerItem);

11. Set the adapter – oncreate

mDrawerList.setAdapter(adapter);

12. create the item click listener DrawerItemClickListener.java

private class DrawerItemClickListener implements ListView.OnItemClickListener {
   
    @Override
    public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
        selectItem(position);
    }
   
}

private void selectItem(int position) {
   
    Fragment fragment = null;
   
    switch (position) {
    case 0:
        fragment = new CreateFragment();
        break;
    case 1:
        fragment = new ReadFragment();
        break;
    case 2:
        fragment = new HelpFragment();
        break;

    default:
        break;
    }
   
    if (fragment != null) {
        FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

        mDrawerList.setItemChecked(position, true);
        mDrawerList.setSelection(position);
        getActionBar().setTitle(mNavigationDrawerItemTitles[position]);
        mDrawerLayout.closeDrawer(mDrawerList);
       
    } else {
        Log.e("MainActivity", "Error in creating fragment");
    }
}

13. Create the needed fragments and the views to inflate in res/layout/

(i.e. CreateFragment.java => res/layout/fragment_create.xml)

CreateFragment.java

public class CreateFragment extends Fragment {

    public CreateFragment() {
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View rootView = inflater.inflate(R.layout.fragment_create, container, false);

        return rootView;
    }

}

fragment_create.xml

<?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="match_parent" >

    <TextView
        android:id="@+id/txtLabel"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:text="Create View"
        android:textSize="16dp" />

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/txtLabel"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="10dp"
        android:src="@drawable/ic_action_copy" />

</RelativeLayout>

14. Set the item click listener – oncreate

…and Inside MainActivity.java

mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

15. try to run – swipe your finger left to right – it works!

As of this stage, the app icon is useless to the nav drawer. It cannot trigger the nav drawer. This is what will be our next steps.

16. For app icon control for nav drawer, add new property on MainActivity

ActionBarDrawerToggle mDrawerToggle;

17. add ic_drawer.png in res/drawable-hdpi/

18. add open and close description in values/string/

<string name="drawer_open">Open navigation drawer</string>
<string name="drawer_close">Close navigation drawer</string>

19. Set properties for proper title display

private CharSequence mDrawerTitle;
private CharSequence mTitle;

..and inside onCreate, after setContentView

mTitle = mDrawerTitle = getTitle();

20. Add the app icon control code inside MainActivity oncreate

mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
mDrawerToggle = new ActionBarDrawerToggle(
        this,
        mDrawerLayout,
        R.drawable.ic_drawer, 
        R.string.drawer_open, 
        R.string.drawer_close 
        ) {
   
    /** Called when a drawer has settled in a completely closed state. */
    public void onDrawerClosed(View view) {
        super.onDrawerClosed(view);
        getActionBar().setTitle(mTitle);
    }

    /** Called when a drawer has settled in a completely open state. */
    public void onDrawerOpened(View drawerView) {
        super.onDrawerOpened(drawerView);
        getActionBar().setTitle(mDrawerTitle);
    }
};

mDrawerLayout.setDrawerListener(mDrawerToggle);

getActionBar().setDisplayHomeAsUpEnabled(true);
getActionBar().setHomeButtonEnabled(true);

21. Add onOptionsItemSelected() method

This is really needed to make app icon a toggle of nav drawer.

@Override
public boolean onOptionsItemSelected(MenuItem item) {
   
   if (mDrawerToggle.onOptionsItemSelected(item)) {
       return true;
   }
  
   return super.onOptionsItemSelected(item);
}

22. Override setTitle() method

This is really needed for changing titles.

@Override
public void setTitle(CharSequence title) {
    mTitle = title;
    getActionBar().setTitle(mTitle);
}

and then change this line

getActionBar().setTitle(mNavigationDrawerItemTitles[position]);

to this line

setTitle(mNavigationDrawerItemTitles[position]);

23. onPostCreate() method

This is really needed to change the up caret icon before the app icon

@Override
protected void onPostCreate(Bundle savedInstanceState) {
    super.onPostCreate(savedInstanceState);
    mDrawerToggle.syncState();
}

Lower Android (2.2+) Version Compatibility

Android Navigation Drawer only works for Honeycomb and Up. To make it work with pre-honeycome devices, you should use the Android support library. Download it first using your SDK manager and then follow the step by step guide here.

This link might also help you.

I found the following video helpful too.

http://stackoverflow.com/q/17388574
https://developer.android.com/design/patterns/navigation-drawer.html
http://developer.android.com/training/implementing-navigation/nav-drawer.html

75 replies
    • ninjazhai
      ninjazhai says:

      Hey Tomesh, do you mean you don’t want to show any launcher icon in your app? How about replacing it with a blank png file?

      Reply
  1. Joe
    Joe says:

    Hi, I’m having error in the DrawerItemClickListener.java with the getFragmentManager() and getActionBar(). How to fix those?

    Reply
    • ninjazhai
      ninjazhai says:

      Hey Joe, would you give us the logcat of that error? We cannot fix it unless we know what exactly is the issue.. Thanks!

      Reply
      • Edwin Dico Okugbo
        Edwin Dico Okugbo says:

        Its an error that doesnt allow the code to compile, not a run time error. It cant seem to resolve getFragmentManager(), mDrawerList, getActionBar() and mDrawerLayout. And alt-Enter doent help too. I think something is missing in the code maybe.

        Reply
  2. Anthony Olsen
    Anthony Olsen says:

    Is there any tutorial on how to make the fragments within a navigation drawer scrollable? I attempted to add a ScrollView to the XML file, but it caused the app to crash unexpectedly.

    Reply
    • ninjazhai
      ninjazhai says:

      Hey @anthonyolsen:disqus , I think if you have several items on the navigation, it will scroll automatically, have you tried it? Else, thanks for this blog post suggestion!

      Reply
  3. Rabbi Hardar
    Rabbi Hardar says:

    Hi there. I have been manipulating a little bit with this awsome code, trying to make the listview expandable, but without success. Do you have any suggestions?

    Reply
    • ninjazhai
      ninjazhai says:

      Hi @RabbiHardar:disqus, glad you found this code awesome! I haven’t tried it with expandable listview, but thanks for this possible blog post suggestion!

      Reply
  4. killesk
    killesk says:

    Hey, nice code. I’m trying to download the source code but I’m getting:

    Fatal error: Cannot re-assign auto-global variable _POST in /home/content/73/11827973/html/download-coan/objects/demo.php on line 66

    Paul

    Reply
    • ninjazhai
      ninjazhai says:

      You’re welcome Paul @disqus_WdSKofqD9U:disqus! And thanks for bringing this error to my attention, I recently upgraded my PHP version, maybe that’s the reason why it occurred. But anyway, it’s fixed now, you can download the source code! :)

      Reply
  5. JJ
    JJ says:

    Hi, I’m having the same joe’s error. In step 12:

    Error:(21, 13) error: class, interface, or enum expected
    Due to the bracket that close DrawerItemClickLister

    And aslo in that code:

    if (fragment != null) {
    FragmentManager fragmentManager = getFragmentManager();
    fragmentManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

    mDrawerList.setItemChecked(position, true);
    mDrawerList.setSelection(position);
    getActionBar().setTitle(mNavigationDrawerItemTitles[position]);
    mDrawerLayout.closeDrawer(mDrawerList);
    }

    Cannot resolve:
    getFragmentManager
    mDrawerList
    getActionBar
    and so on…

    What can I do?
    Thanks!

    Reply
    • Nico
      Nico says:

      Step 12 needs to added to your MainActivity.java file and not a separate class.

      Make sure to copy to import all the items. Here is the full list.

      import android.os.Bundle;
      import android.app.Activity;
      import android.app.Fragment;
      import android.app.FragmentManager;
      import android.support.v4.app.ActionBarDrawerToggle;
      import android.support.v4.widget.DrawerLayout;
      import android.util.Log;
      import android.view.Menu;
      import android.view.MenuItem;
      import android.view.View;
      import android.widget.AdapterView;
      import android.widget.ListView;

      Reply
  6. Chaker
    Chaker says:

    Do not use ActionBar , instead use Toolbar . It is a new powerful class added recently in the support library version set which allows you to deal with animated icons .

    Reply
  7. Jacob Edholm
    Jacob Edholm says:

    If I want to use the same fragment for multiple options in the drawer but change the textview depending on what item i selected, how do I do that?

    Reply
    • ninjazhai
      ninjazhai says:

      @jacobedholm:disqus, you just have to create something like the step 13, put the textview inside onCreateView() and maybe add some on click listener…

      Reply
  8. Edwin Dico Okugbo
    Edwin Dico Okugbo says:

    There is an error that doesnt allow the code to compile in DrawerItemClickListener.java. It cant seem to resolve getFragmentManager(), mDrawerList, getActionBar() and mDrawerLayout. And alt-Enter doent help too. I think something is missing in the code maybe.

    Reply
  9. Manuel Schmitt
    Manuel Schmitt says:

    I did everything step by step, i have no error at compile time, but the onItemClick-Event is never fired.

    What could have gone wrong here?

    Reply
  10. dashhund
    dashhund says:

    Is it still possible to download the source code? I just tried to enroll for subscription so I can download the source code but i’m not receiving any confirmation mails

    Reply
  11. nruiz
    nruiz says:

    Hi ! Thx for your tuto. but i need help on one thing !
    I don’t understant the line: fragment = new ReadFragment(). What is this method ? it’s about fragment_read.xml ? How the link is do ?
    Thx in advance.
    NR.

    Edit: I found. Sorry i didn’t see, ReadFragment.java and HelpFragment.java
    Thx again :)

    Reply
  12. Lehi Thomas
    Lehi Thomas says:

    I’m getting a NullPointerException on this line:

    getActionBar().setDisplayHomeAsUpEnabled(true);

    I’m also getting that ActionBarDrawerToggle is deprecated for android.support.v4.app

    Any suggestions?

    Reply
  13. venkatesh subramanian
    venkatesh subramanian says:

    private void selectItem(int position) {

    Fragment fragment;

    switch (position) {

    case 0:

    “fragment = new FirstFragment();”

    break;

    case 1:

    “fragment = new SecondFragment();”

    break;

    default:

    break;

    }

    all the things are went good except this error..represented in double quotes it says that “Type mismatch: cannot convert from FirstFragment to Fragment” plz reply me .thanks in advance

    Reply
  14. ashish
    ashish says:

    I have followed the same code but when i try to add new fragment the app crashes,can you please tell the possible cause?

    Reply
  15. Federico
    Federico says:

    Hi, I want to report that the registration e-mail isn’t working anymore; I tried to register with 2 different e-mails but with no success.
    I want also to highlight some wrong parts in your code (maybe they aren’t wrong, but with your code it doesn’t work).
    Whoever gets a NullPointerException on getActionBar(), change getActionBar() to getSupportActionBar() (in each call of the method).
    Hope this helps someone :)
    BTW, I believe it would be useful if you fix the registration mail, so users can download the entire code.

    Thanks for this nice tutorial!

    Reply
  16. Mike Dalisay
    Mike Dalisay says:

    Hello @disqus_MKOHlmxstk:disqus, did you check your spam folder? Thanks for reporting about it and your tips! I’ll work on updating the registration email soon.

    Reply
    • Federico
      Federico says:

      I’ve just checked but unfortunately the e-mail wasn’t in the spam folder. Anyway, I’m glad to hear that! Keep on your good work.

      Reply
  17. Amar
    Amar says:

    Hi, I followed all the steps mentioned by you here , but still getting compilation issues.
    Do you have a link of working code to download ? thanks

    Reply
  18. NM
    NM says:

    Hello there, I’m new at android application and I’m having an error at step 20:

    mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
    mDrawerToggle = new ActionBarDrawerToggle( <——- ActionBarDrawerToggle is
    deprecated

    this,
    mDrawerLayout,
    R.drawable.ic_drawer,
    R.string.drawer_open,
    R.string.drawer_close
    ) {

    /** Called when a drawer has settled in a completely closed state. */
    public void onDrawerClosed(View view) {
    super.onDrawerClosed(view);
    getActionBar().setTitle(mTitle);
    }

    /** Called when a drawer has settled in a completely open state. */
    public void onDrawerOpened(View drawerView) {
    super.onDrawerOpened(drawerView);
    getActionBar().setTitle(mDrawerTitle);
    }
    };

    mDrawerLayout.setDrawerListener(mDrawerToggle);

    getActionBar().setDisplayHomeAsUpEnabled(true); <—— Attempt to invoke virtual method 'void
    android.app.ActionBar.setDisplayHome
    AsUpEnabled(boolean)' on a null object
    reference

    getActionBar().setHomeButtonEnabled(true);

    Can someone help me?
    Thanks in advance.

    Reply
  19. Rajesh
    Rajesh says:

    Hi,
    Very nice tutorial for android beginners like me. I tried the above code with my application. Here I am facing a problem. For me only title is changing after selecting menu item from navigation drawer, View is not replacing.

    Reply
  20. Amarendra Kumar
    Amarendra Kumar says:

    Thanks for the tutorial but i have one query , ho to change the drawer color from black to some other thanks in advance.

    Reply
  21. ‫נדב תמים‬‎
    ‫נדב תמים‬‎ says:

    hey my friend, first of all tnx for this manual its great.

    i have a problem that after i made all the steps, i opend the drawer from main activity and its work well but other buttons or listview in main activity does’nt work at all, not responding

    Reply
  22. Ann_pyon
    Ann_pyon says:

    hi, its a good tutorials. I try step by step carefully, When I try on the break, Its run well, but when I click the “Create” menu, it make force close. I think it should be go to createfragment the view fragment-create. may be someone can give me suggest what to do?

    Reply
  23. kelvin audian
    kelvin audian says:

    hi!, i’m having error in step 12, here is my error:
    Error:(49, 28) error: incompatible types
    required: Fragment
    found: CreateFragment

    Error:(52, 28) error: incompatible types
    required: Fragment
    found: ReadFragment

    Error:Execution failed for task ‘:app:compileDebugJavaWithJavac’.
    > Compilation failed; see the compiler error output for details.

    and my program can’t resolve this code:
    switch (position) {
    case 0:
    fragment = new CreateFragment();
    break;
    case 1:
    fragment = new ReadFragment();
    break;

    default:
    break;
    }

    anyone please give me the suggest… thanks

    Reply
  24. Priya (DLS)
    Priya (DLS) says:

    Hi,

    I have downloaded this code and made a project of my own following the step by step instructions. Im using Eclipse Juno.

    In the MainActivity.java the line import android.support.v4.app.ActionBarDrawerToggle; shows deprecated. If i change the import to v7 then the new ActionBarToggle line gives an error.

    Please guide where im going wrong. My manifest

    Thanks in advance.

    Reply

Leave a Reply

Want to join the discussion?
Feel free to contribute!

Leave a Reply

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