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.
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
77 responses to “Android Navigation Drawer Example Step by Step”
How to remove the launcher Icon on the action bar in your code ????
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?
Hi, I’m having error in the DrawerItemClickListener.java with the getFragmentManager() and getActionBar(). How to fix those?
Hey Joe, would you give us the logcat of that error? We cannot fix it unless we know what exactly is the issue.. Thanks!
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.
thanks for share your awasomeness :)
Hey @krishna, thanks for sharing your thoughts, you’re awesome too because of that!
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.
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!
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?
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!
Hi, The landing page is blank. How do we make it default to create fragment ?
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
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! :)
Hello! Thanks.
Source archive is broken.
Hello @valentynchub:disqus, thanks for letting me know! Sorry for the inconvenience. It’s fixed now.
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!
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;
DrawerItemClickListener.java is not a class, don’t make new class, it’s a method in MainActivity.java
how can i create navigation drawer while there are listview in activity_main layout?
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 .
Hello @Chaker, thanks for the tip! Would you give us a link or resource related to it?
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?
@jacobedholm:disqus, you just have to create something like the step 13, put the textview inside onCreateView() and maybe add some on click listener…
Do you mean I can replace “fragment = new CreateFragment();” with “text.SetText=(“test”)” in the switch statement?
If I add a click listener at the onCreateView() how will I get the position for the switch statement?
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.
how can i assign a button action in the first fragment?
Pretty Good article. Got it right in the first place. Thanks for sharing
Hello @hhimanshu:disqus, glad you make it work the first time! :)
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?
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
Hello dashhund, we’re currently fixing things for our source code download, thanks for you patience!
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 :)
Sorry, but I dont see it. What line number is it? I’m using Ctrl-F and nothing comes up. Thanks!!
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?
Try getSupportActionBar()
Dear Don’t Give half Code to all where are the Remaining Methods that you are not Shown above
Hello @ninjaka baap, I believe I published all the codes above, which part of the code is missing for you?
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
you need to import android.support.v4.app.Fragment; to your FirstFragment
I have followed the same code but when i try to add new fragment the app crashes,can you please tell the possible cause?
Hello @ashish, would you paste the logcat error?
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!
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.
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.
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
Hello @Amar, would you be more specific and give us the compilation error messages? Thanks a lot! We are working to give a download link.
Hei guys, anyone who gets error in DrawerItemClickListener.java , it’s not a class, it should be a method of MainActivity.java , just try to match the codes after following this tutorial.
How to add material design in this code?
Hello @bhavikshah92:disqus, we will do that in the future, thanks for your suggestion…
how can hide text title in action bar please help me
Hi.. Code works fine.. Thanks
Hello @Vinod, thanks for visiting and letting us know this works fine :)
Hello Prakash Kumar, how about setTitle(“My new title”);
You can read more http://stackoverflow.com/questions/14483393/how-do-i-change-the-android-actionbar-title-and-icon
yes
thanks
You’re welcome @disqus_22PtwEcUZE:disqus!
thanks
how can implement wsdl web service in android studio please help me
WSDL is XML based, I recommend you use JSON instead, here’s a sample code https://www.codeofaninja.com/2013/11/android-json-parsing-tutorial.html
how can implement wcf service in android apps ..
He gives me wcf service
Please help me how can implement and What is process how can do
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.
get it what i find from last 2 days… easy,nice and clean.. great work..
thnx..
Hello @disqus_QCIgxgMAop:disqus, thanks for your kind words. Glad it worked for you!
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.
Thanks for the tutorial but i have one query , ho to change the drawer color from black to some other thanks in advance.
How to change selected item background color ??
that concern item xml file give white color to below example
<android:backgroudcolor="#ffffff"
navigation drawer with dynamic values via services if any one help
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
How can we apply same navigation drawer on all activities?
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?
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
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.
ReadFragment()
getFragmentManager()
mDrawerList error?
Could you explain about that?
Great tutoril. But when i add another draerItem[3] object the app crashes. can anyone tell me why?