You are on page 1of 10

13/2/2015

NavigationDrawerAndroidExample|JavaTechig

About

Home

Our Team

Write for us

Java Tutorials

Advertise

Android

Search

Contact us

Xamarin

Other Tutorials

Blog

Search

Sample Apps
Javatechig

Navigation Drawer Android Example


Posted on Oct 16, 2013 by Nilanchala in Android with 46
Comments

Follow

Like

20

Follow@javatechig

210followers

6,891peoplelikeJavatechig.

Connect with us

Table of Contents
Facebooksocialplugin

1. Navigation Drawer Design


2. When to Use the Navigation Drawer

Sign up to receive email updates when

3. Creating a Navigation Drawer

a new tutorial is added.

3.1. Create a Drawer Layout


3.2. Initialize the Drawer List
3.3. Handle Navigation Click Events
3.4. Listen for Open and Close Events

Email Subscribe

Subscribe

4. Download Complete Source


5. Working Demo

Categories
Thenavigation drawer is a panel that displays the apps main

Android

navigation commands on the left side of the screen. It is not visible by

Books

default, and can be shown while user swipes right or while clicking on

Cross Platform

the open menu icon in the ActionBar. This example describes How to

Design

implement a navigation drawer using Support

Gaming

Librarythe DrawerLayout API.

IBM Worklight

1. Navigation Drawer Design


Navigation drawer is an overlay panel, that is replaced with the legacy
application dashboard screen or menu. Now we dont need to create a
dedicated activity for showing all application options. For example, if

Apps

Core Java

Libgdx

Git

Data Structures

Tools

Eclipse

HTML5
J2ME

Mac OS X

Java

Open Source

Reviews

Sencha Touch

Blog

C Programming

Design Patterns

PhoneGap

Tips

Blackberry

SE Concepts

Servlets
Video

Struts

Wordpress

Xamarin

you look at the older version of Facebook app, the dashboard screen
was only the way to play around with the app. Lets say, if you are
inside messages, you wont be able to get into the friends list, unless
you come back to dashboard.

http://javatechig.com/android/navigationdrawerandroidexample

1/10

13/2/2015

NavigationDrawerAndroidExample|JavaTechig

Javatechig
Like

6,891peoplelikeJavatechig.

Facebooksocialplugin

The latest version of Facebook App is using the Navigation Drawer.

2. When to Use the Navigation Drawer


Before you decide to use a navigation drawer in your app, you should
understand the use cases and design principles defined in
theNavigation Drawerdesign guide. It is not an general replacement
for top-level menu navigation.
More information on design guidelines follow here.

3. Creating a Navigation Drawer


This lesson describes step by step tutorial to Implement a navigation
drawer using the DrawerLayout APIs available in the Support Library.

3.1. Create a Drawer Layout


To create a navigation drawer, first declare your user interface with a
DrawerLayout object as the root view of your layout.
Inside the DrawerLayout, add one view that contains the main content
for the screen (your primary layout when the drawer is hidden) and
another view that contains the contents of the navigation drawer. In
this example, our layout uses a DrawerLayout with two child views.
One FrameLayout to contain the main content, and a ListView for the
navigation drawer. The FrameLayout is used to hold the child views
populated by a Fragment at runtime.
<android.support.v4.widget.DrawerLayoutxmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/drawer_layout"
android:layout_width="match_parent"
android:layout_height="match_parent">
<!Themaincontentview>
http://javatechig.com/android/navigationdrawerandroidexample

2/10

13/2/2015

NavigationDrawerAndroidExample|JavaTechig

<FrameLayout
android:id="@+id/content_frame"
android:layout_width="match_parent"
android:layout_height="match_parent"/>
<!Thenavigationdrawer>
<ListView
android:id="@+id/drawer_list"
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>

Key Notes:
The main content view is used as first child in the
DrawerLayout. The XML order implies z-ordering and the
drawer must be on top of the content.
The main content view is set to match the parent views width
and height, because it represents the entire UI when the
navigation drawer is hidden.
The drawer view specifies its width in dp units and the height
matches the parent view. The drawer width should be no more
than 320dp so the user can always see a portion of the main
content.

3.2. Initialize the Drawer List


Now, first initialize the navigation drawers list of items. As here the
navigation drawer consists a ListView, so the list can be populated by
an Adapter.
//Withinwhichtheentireactivityisenclosed
privateDrawerLayoutmDrawerLayout;
//ListViewrepresentsNavigationDrawer
privateListViewmDrawerList;
//GettingreferencetotheDrawerLayout
mDrawerLayout=(DrawerLayout)findViewById(R.id.drawer_layout);
mDrawerList=(ListView)findViewById(R.id.drawer_list);
//CreatinganArrayAdaptertoadditemstothelistviewmDrawerList
ArrayAdapter<String>adapter=newArrayAdapter<String>(getBaseContext

R.layout.drawer_list_item,getResources().getStringArray
//SettingtheadapteronmDrawerList
mDrawerList.setAdapter(adapter);
http://javatechig.com/android/navigationdrawerandroidexample

3/10

13/2/2015

NavigationDrawerAndroidExample|JavaTechig

3.3. Handle Navigation Click Events


When the user selects an item in the drawers list, the system calls
onItemClick() on the OnItemClickListener given to
setOnItemClickListener(). In this example, selecting each item in the
list inserts a different Fragment into the main content view
FrameLayout.
//SettingitemclicklistenerforthelistviewmDrawerList
mDrawerList.setOnItemClickListener(newOnItemClickListener(){

@Override
publicvoidonItemClick(AdapterView&lt;?&gt;parent,Viewview,
intposition,longid){

//Gettinganarrayofrivers
String[]menuItems=getResources().getStringArray(R.array.

//Currentlyselectedriver
mTitle=menuItems[position];

//Creatingafragmentobject
WebViewFragmentrFragment=newWebViewFragment();

//Passingselectediteminformationtofragment
Bundledata=newBundle();
data.putInt("position",position);
data.putString("url",getUrl(position));
rFragment.setArguments(data);

//GettingreferencetotheFragmentManager
FragmentManagerfragmentManager=getFragmentManager();

//Creatingafragmenttransaction
FragmentTransactionft=fragmentManager.beginTransaction();

//Addingafragmenttothefragmenttransaction
ft.replace(R.id.content_frame,rFragment);

//Committingthetransaction
ft.commit();

//Closingthedrawer
mDrawerLayout.closeDrawer(mDrawerList);

}
});

3.4. Listen for Open and Close Events


We can also listen to the drawer open and close event. To listen for
drawer open and close events, we can extend the
ActionBarDrawerToggle class. The ActionBarDrawerToggle
implements DrawerLayout.DrawerListener.
//GettingreferencetotheActionBarDrawerToggle
mDrawerToggle=newActionBarDrawerToggle(this,mDrawerLayout,
http://javatechig.com/android/navigationdrawerandroidexample

4/10

13/2/2015

NavigationDrawerAndroidExample|JavaTechig

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

/**Calledwhendrawerisclosed*/
publicvoidonDrawerClosed(Viewview){
getActionBar().setTitle(mTitle);
invalidateOptionsMenu();
}

/**Calledwhenadrawerisopened*/
publicvoidonDrawerOpened(ViewdrawerView){
getActionBar().setTitle("JAVATECHIG.COM");
invalidateOptionsMenu();
}

};
//SettingDrawerToggleonDrawerLayout
mDrawerLayout.setDrawerListener(mDrawerToggle);

4. Download Complete Source


Download Source Code on Github

5. Working Demo

Nilanchala
A blogger, a bit of tech freak and a software developer. He is a
thought leader in the fusion of design and mobile technologies.
Follow him on Twitter or Google plus.

Related Posts

http://javatechig.com/android/navigationdrawerandroidexample

5/10

13/2/2015

NavigationDrawerAndroidExample|JavaTechig

How to Get List of


Installed Apps in
Android

46Comments

How to Drag a
View in Android

Android Toast
Example

Setting
ANDROID_HOME
Environmental
Variable on Mac

javatechig

Login

Share Favorite

SortbyNewest

Jointhediscussion
santiagop593 15daysago

Thanksalot!!awesometutorial
CheckoutmycryptographyappthatusesNavigationDrawers
https://play.google.com/store/...

Reply Share

WasimMemon amonthago

heyhowcanislidemainlayouttowardtheright(asperlinkdinstyle).?

Reply Share

arnold 3monthsago

howcaniaddthegridviewasthemaincontentinthisdrawer....havenoclue
onhowtodothat
1

Reply Share

Zafer 3monthsago

HowcanIhandlebothactivityandfragmentonNavigationDrawer?
1

Reply Share

RyanPedersen 3monthsago

hereisaslightimprovementtothesettingsmenuhiding
http://toastdroid.com/2014/04/...

Reply Share

SaimonAlam 4monthsago

Heyman,Ilearnedalotfromthis.Thanks4thegreattutorial.ButwhatI'm
puzzledabtisthatwhenIclickonanitemonthedrawerthetitleonthe
actionbarchangesandthedrawerclosesbutIstillgetablankpage.Itseems
2methatthefragmentisnotgettingloadedatall.
IshouldalsomentionthatIcouldn'timporttheproject2eclipsedirectlybcozit
didnotrecognizeitasavalidproject.SoIsimplycreatedthejavaandXML
fileswiththeexactsamenamesasintheprojectandcopiedtheimagesand
stringresourcesandIdidaddinternetpermissioninthemanifestaswell.
Everythingworksexcept4thefragmentpart.
Anyhelpwillbemorethanappreciated.Thanksalot.

Reply Share

MishaLashkov 4monthsago

Hi,thanksfortheawesomecode,onequestionthough,whenstartingthe
http://javatechig.com/android/navigationdrawerandroidexample

6/10

13/2/2015

NavigationDrawerAndroidExample|JavaTechig

Hi,thanksfortheawesomecode,onequestionthough,whenstartingthe
applicationitwillshowablankpage,couldyoumodifythecodesoitwillstart
withcase0(home)?
Thankyou!
1

Reply Share

JavaTechig

Mod >MishaLashkov

4monthsago

Thanksforyoursuggestions.Wewilldotherequiredchanges.

Reply Share

SanjayjithM 4monthsago

IcreatedoneapplicationandIusednavigationdrawertonavigatefromone
fragmenttoanother.Inthat,ifInavigatefromonefragmenttoanotherandif
againcomebacktothesamefragment.Itsnotgettingresume.Itssimply
showingUnfortunatelytheappwasclosed.Canyoutellmehowtouse
onresumemethodproperlyinfragment???

Reply Share

JavaTechig

Mod >SanjayjithM

4monthsago

canyoupastetheerrormessagehere?

Reply Share

osamaakb 4monthsago

i'mbeginnerineclipseandidownloadedthesourcecode,iwanttoopenitbut
idontknowhowtoopenit

Reply Share

JavaTechig

Mod >osamaakb

4monthsago

Juststarteclipse.InyourworkspaceclickFile>Import>Existing
androidcodeintoworkspace.

Reply Share

osamaakb 4monthsago

goodjobdude.butiwanttomakenavigationdrawerthatletmelike.for
exampleificlickedonandroiditopenawebview(url)

Reply Share

javatechig 5monthsago

howtogetthis

Reply Share

JavaTechig

Mod >javatechig

5monthsago

Checkoutthislib..
https://github.com/jfeinstein1...
BydefaultinandroidNavigationmenu,youcannotmovetheactionbar
whilemenuisopen.Butyoucanachievewiththeabovegithubcode.

Reply Share

javatechig>JavaTechig 5monthsago

whatidoforgetting
thatexactscreenshotinandroid

Reply Share
http://javatechig.com/android/navigationdrawerandroidexample

7/10

13/2/2015

NavigationDrawerAndroidExample|JavaTechig

Reply Share

javatechig>JavaTechig 5monthsago

BywhichConceptitisPossiblecorrectlyasabovescreenshot
shown

Reply Share

javatechig 5monthsago

Howtogetthiswilluplsheipmeplssendthecodeforthis

Reply Share

Bruno 6monthsago

Iloveyou!

Reply Share

Thibautfrance 6monthsago

Hello,greatjob,ihaveonequestion,howtoaddicoforeachmenusideby
side.
Answerpleasethanks

Reply Share

DavidePirelli 6monthsago

greattutorialman,allworkingperfectly..but...howcaniimplementonBack()
historyinwebviewsfragment?

Reply Share

DavidePirelli 6monthsago

Howcanimakeafunctionthat"goBack"inhistoryofawebviewfragment?
BTWthisguiderule!Greatworks,allofyourguidearewellwrittenandsimple
tounderstand)

Reply Share

DavidePirelli 6monthsago

Howcaniget"onestepback"withbackbutton?
Thanksinadvance!

Reply Share

JermaineThomas 7monthsago

Hey,lovelysampleapp.Myonlyproblemiseachoftheitemsinthemenu
openstheurlinthebrowser(outsideoftheapp)canyoupleaseadvise.

Reply Share

JavaTechig

Mod >JermaineThomas

7monthsago

whichappordeviceareyoutestingon?

Reply Share

JermaineThomas>JavaTechig 7monthsago

Hey,testingonos4.2.2butisawtheproblem,therewasno
webclientviewinitiated.Soiaddedthelinebelowjustbefore
webView.loadUrl(url)intheWebViewFragment.javafile
http://javatechig.com/android/navigationdrawerandroidexample

8/10

13/2/2015

NavigationDrawerAndroidExample|JavaTechig

webView.setWebViewClient(newWebViewClient())
1

Reply Share

Coziie 7monthsago

FirsteverAndroidsampleIdownloadedfromwebworked!!I'mnewtoJava
andneverhadasuccessinrunningademoappdownloadedfromweb.
Your'sisthefirstworkingsampleofAndroidifoundonline.Thankyouvery
much.
1

Reply Share

JavaTechig

Mod >Coziie

7monthsago

Thanksforreading.
1

Reply Share

Harsh 7monthsago

Thisisbyfarthebesttutorial.

Reply Share

JorellRutledge 8monthsago

Howwouldyouaddiconstothenavigationdrawer?Also,howwouldyou
enablethewebviewtogoback?Anyhelpwouldbeamazing.
1

Reply Share

thibautfrance>JorellRutledge 6monthsago

YEsjavatechig,itwouldbeperfect:)

Reply Share

Madiyar 8monthsago

Howdoswipewithactionbarlikethispicture

Reply Share

JavaTechig

Mod >Madiyar

6monthsago

Thisisnomoreaandroiddesignpattern.Suggesttogowithdefault
androidguidelines.

Reply Share

AdrianComan 10monthsago

ThisrequiresAPIlevel11,soit'savailableforAndroid3.0+ifi'mnotmistaken.
1

Reply Share

JavaTechig

Mod >AdrianComan

10monthsago

Yes,theaboveexampleworks3.0+

Reply Share

Bastien ayearago

niceexample.Butthereisanissue.Ifmyfragmentisdoingtoomuchof
backgroundworkthenavigationclosingiscausingadelay.Anyworkaround
onthis?

Reply Share

JavaTechig

Mod >Bastien

12daysago

http://javatechig.com/android/navigationdrawerandroidexample

9/10

13/2/2015

NavigationDrawerAndroidExample|JavaTechig

Yes,dothefragmenttransactionononDrawerClosed()

Reply Share

Kenito ayearago

Icantdownloadthesourcecode
1

Reply Share

vortex67 ayearago

Webviewworksonlywithnavigationdrawerwhileapplicationstartswitha
blankpage.
1

Reply Share

JavaTechig

Mod >vortex67

7monthsago

Itisjustanexampleofnavigationdrawer.Youcanfixsuchbugs
1

Reply Share

MaheshVemuri ayearago

willitworkonandroid2.3?

Reply Share

MaheshVemuri ayearago

Willthisworkonandroid2.3?

Reply Share

JavaTechig

Mod >MaheshVemuri

12daysago

Currentlytheexampleisdevelopedfor4.0andabove

Advertise|Contact us|Privacy Policy | Terms of Use

http://javatechig.com/android/navigationdrawerandroidexample

2012-2015 JavaTechig All rights reserved.

10/10

You might also like