Android Sliding Menu Navigation like Facebook App

By January 7, 2014 Android, Mobile, Mobile UX 3 Comments
Navigation Drawer

Google’s new UI pattern, “Android Navigation Drawer” a.k.a Sliding Menu Navigation, was introduced in the Google I/O 2013 held in May. The UI Pattern is mostly used in famous Apps like Facebook, Google +, Google Keep, Evernote, Youtube, Foursquare,Zappos, LinkedIn and Handouts etc.

It’s Guideline and sample can be found in detail in the android support library v13, but I’d mention an approach pretty straight forward like piece of cake with Source Code.

Before you decide to use a navigation drawer in your app, you should know What, Where/When, and How an App uses Navigation Drawer

Navigation Drawer

What is Navigation Drawer (Sliding Menu Navigation)?

Navigation drawer is a panel that enables displaying of an app’s main navigation option on the left edge of the screen. The drawer is hidden most of the time, only to reveal when the user swipes a finger from the left edge of the screen or when the user touches the action bar’s app icon while at the app’s top level.

When to use Navigation Drawer in your apps?

Navigation Drawer is not a replacement for the general spinners or tabs that most apps use. Each of them have their own features, and it is the Structure of your app that should help choose the correct UI pattern suitable for top level switching screens/Activities. Design Structure document is in detail here

How to use Navigation Drawer

First download the ic_drawer.png icon from here. It should be placed in drawable-hdpi, drawable-xhdpi and drawable-xxhdpi folders. It can also be downloaded from the link at the end of the page.

XML FILES

In the main_activity.xml file, the newly introduced UI DrawerLayout acts as a top-level container for window content that allows for interactive “drawer” views to be pulled out from the edge of the window.
Drawer positioning and layout is controlled using the android:layout_gravity attribute on child views corresponding to which side of the view you want the drawer to emerge from: left or right. In our case we are doing with left.
Position your primary content view as the first child with a width and height of match_parent. Add drawers as child views after the main content view and set the layout_gravity appropriately. Drawers commonly use match_parent for height with a fixed width.

main_activity.xml

  1. <android.support.v4.widget.DrawerLayout
  2. xmlns:android=”http://schemas.android.com/apk/res/android”
  3. android:id=”@+id/drawer_layout”
  4. android:layout_width=”match_parent”
  5. android:layout_height=”match_parent”>
  6. <!– Displaying Fragments –>
  7. <FrameLayout
  8. android:id=”@+id/frame_container”
  9. android:layout_width=”match_parent”
  10. android:layout_height=”match_parent”
  11. />
  12. <!– Displaying Drawer –>
  13. <ListView
  14. android:id=”@+id/list_slidermenu”
  15. android:layout_width=”240dp”
  16. android:layout_height=”match_parent”
  17. android:layout_gravity=”left”
  18. android:choiceMode=”singleChoice”
  19. android:divider=”@color/list_divider”
  20. android:dividerHeight=”1dp”
  21. android:listSelector=”@drawable/drawer_list_selection”
  22. android:background=”@color/list_background”/>
  23. </android.support.v4.widget.DrawerLayout>

Adding your strings (Like Toasts, Messages Warnings) to strings.xml enables you to easily translate the app into other languages. The strings.xml is located in folder values.
by doing this, it saves you extra work which would have been done the hard coded way. Also, there aren’t any warnings of hard coded text in the xml file during development.
We are saving data and List Item Icons in two arrays name nav_drawer_items and nav_drawer_icons respectively that we will access from our MainActivity.java class
Added Menu Strings Like “Setting” “Rate App” etc enables you to add Menu as your app requirements in actionbar.

strings.xml

  1. <?xmlversion=”1.0″encoding=”utf-8″?>
  2. <resources>
  3. <stringname=”app_name”>Navigation Drawer</string>
  4. <!– Menu Strings –>
  5. <stringname=”action_settings”>Settings</string>
  6. <stringname=”action_rateapp”>Rate App</string>
  7. <stringname=”action_refresh”>Refresh</string>
  8. <stringname=”hello_world”>Hello world!</string>
  9. <!– Navigation Drawer Menu Items –>
  10. <string-arrayname=”nav_drawer_items”>
  11. <item>Home</item>
  12. <item>Facebook</item>
  13. <item>Google</item>
  14. <item>Apple</item>
  15. <item>Microsoft</item>
  16. <item>Linkedin</item>
  17. </string-array>
  18. <!– List Item Icons(Images) with strings(text of company name) –>
  19. <!– Keep them with titles array accordingly –>
  20. <arrayname=”nav_drawer_icons”>
  21. <item>@drawable/icon_home</item>
  22. <item>@drawable/facebook</item>
  23. <item>@drawable/google</item>
  24. <item>@drawable/apple</item>
  25. <item>@drawable/windows</item>
  26. <item>@drawable/linkedin</item>
  27. </array>
  28. <!– drawer_list_itemImageview Description –>
  29. <stringname=”description_list_icon”>Item Icon</string>
  30. </resources>

In MainActivity.java, we have declared variables loaded list items Text (Facebook, Google, Apple and so on) with Icons from arrays nav_drawer_items and nav_drawer_icons from strings.xml . We also created an adapter and added list item to it.

MainActivity.java

  1. packagecom.vizteck.navigationdrawer;
  2. importcom.vizteck.navigationdrawer.adapter.NavDrawerListAdapter;
  3. importcom.vizteck.navigationdrawer.model.NavDrawerItem;
  4. importjava.util.ArrayList;
  5. importandroid.os.Bundle;
  6. importandroid.app.Activity;
  7. importandroid.app.Fragment;
  8. importandroid.app.FragmentManager;
  9. importandroid.content.res.Configuration;
  10. importandroid.content.res.TypedArray;
  11. import android.support.v4.app.ActionBarDrawerToggle;
  12. import android.support.v4.widget.DrawerLayout;
  13. importandroid.util.Log;
  14. importandroid.view.Menu;
  15. importandroid.view.MenuItem;
  16. importandroid.view.View;
  17. importandroid.widget.AdapterView;
  18. importandroid.widget.ListView;
  19. public class MainActivity extends Activity {
  20. privateDrawerLayoutmDrawerLayout;
  21. privateListViewmDrawerList;
  22. privateActionBarDrawerTogglemDrawerToggle;
  23. // NavigationDrawer title “Nasdaq” in this example
  24. privateCharSequencemDrawerTitle;
  25. // App title “Navigation Drawer” in this example
  26. privateCharSequencemTitle;
  27. // slider menu items details
  28. private String[] navMenuTitles;
  29. privateTypedArraynavMenuIcons;
  30. privateArrayList<NavDrawerItem>navDrawerItems;
  31. privateNavDrawerListAdapter adapter;
  32. @Override
  33. protected void onCreate(Bundle savedInstanceState) {
  34. super.onCreate(savedInstanceState);
  35. setContentView(R.layout.activity_main);
  36. mTitle = mDrawerTitle = getTitle();
  37. // getting items of slider from array
  38. navMenuTitles =getResources().getStringArray(R.array.nav_drawer_items);
  39. // getting Navigation drawer icons from res
  40. navMenuIcons = getResources()
  41. .obtainTypedArray(R.array.nav_drawer_icons);
  42. mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
  43. mDrawerList = (ListView) findViewById(R.id.list_slidermenu);
  44. navDrawerItems = new ArrayList<NavDrawerItem>();
  45. // list item in slider at 1 Home Nasdaq details
  46. navDrawerItems.add(new NavDrawerItem(navMenuTitles[0],navMenuIcons.getResourceId(0, -1)));
  47. // list item in slider at 2 Facebook details
  48. navDrawerItems.add(new NavDrawerItem(navMenuTitles[1],navMenuIcons.getResourceId(1, -1)));
  49. // list item in slider at 3 Google details
  50. navDrawerItems.add(new NavDrawerItem(navMenuTitles[2],navMenuIcons.getResourceId(2, -1)));
  51. // list item in slider at 4 Apple details
  52. navDrawerItems.add(new NavDrawerItem(navMenuTitles[3],navMenuIcons.getResourceId(3, -1)));
  53. // list item in slider at 5 Microsoft details
  54. navDrawerItems.add(new NavDrawerItem(navMenuTitles[4],navMenuIcons.getResourceId(4, -1)));
  55. // list item in slider at 6 LinkedIn details
  56. navDrawerItems.add(new NavDrawerItem(navMenuTitles[5],navMenuIcons.getResourceId(5, -1)));
  57. // Recycle array
  58. navMenuIcons.recycle();
  59. mDrawerList.setOnItemClickListener(new SlideMenuClickListener());
  60. // setting list adapter for Navigation Drawer
  61. adapter = new NavDrawerListAdapter(getApplicationContext(),
  62. navDrawerItems);
  63. mDrawerList.setAdapter(adapter);
  64. // Enable action bar icon_luncher as toggle Home Button
  65. getActionBar().setDisplayHomeAsUpEnabled(true);
  66. getActionBar().setHomeButtonEnabled(true);
  67. mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
  68. R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {
  69. public void onDrawerClosed(View view) {
  70. getActionBar().setTitle(mTitle);
  71. invalidateOptionsMenu(); //Setting, Refresh and Rate App
  72. }
  73. public void onDrawerOpened(View drawerView) {
  74. getActionBar().setTitle(mDrawerTitle);
  75. invalidateOptionsMenu();
  76. }
  77. };
  78. mDrawerLayout.setDrawerListener(mDrawerToggle);
  79. if (savedInstanceState == null) {
  80. displayView(0);
  81. }
  82. }
  83. // Slider menu item click listener
  84. private class SlideMenuClickListener implements
  85. ListView.OnItemClickListener {
  86. @Override
  87. public void onItemClick(AdapterView<?> parent, View view, intposition,
  88. long id) {
  89. // display view for selected item
  90. displayView(position);
  91. }
  92. }
  93. @Override
  94. publicbooleanonCreateOptionsMenu(Menu menu) {
  95. getMenuInflater().inflate(R.menu.main, menu);
  96. return true;
  97. }
  98. @Override
  99. publicbooleanonOptionsItemSelected(MenuItem item) {
  100. // title/icon
  101. if (mDrawerToggle.onOptionsItemSelected(item)) {
  102. return true;
  103. }
  104. // Handle action bar actions click
  105. switch (item.getItemId()) {
  106. caseR.id.action_settings:
  107. return true;
  108. default:
  109. returnsuper.onOptionsItemSelected(item);
  110. }
  111. }
  112. //called when invalidateOptionsMenu() invoke
  113. @Override
  114. publicbooleanonPrepareOptionsMenu(Menu menu) {
  115. // if Navigation drawer is opened, hide the action items
  116. booleandrawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);
  117. menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
  118. returnsuper.onPrepareOptionsMenu(menu);
  119. }
  120. private void displayView(int position) {
  121. // update the main content with called Fragment
  122. Fragment fragment = null;
  123. switch (position) {
  124. case 0:
  125. fragment = new Fragment1Nasdaq();
  126. break;
  127. case 1:
  128. fragment = new Fragment2Facebook();
  129. break;
  130. case 2:
  131. fragment = new Fragment3Google();
  132. break;
  133. case 3:
  134. fragment = new Fragment4Apple();
  135. break;
  136. case 4:
  137. fragment = new Fragment5Microsoft();
  138. break;
  139. case 5:
  140. fragment = new Fragment6LinkedIn();
  141. break;
  142. default:
  143. break;
  144. }
  145. if (fragment != null) {
  146. FragmentManagerfragmentManager = getFragmentManager();
  147. fragmentManager.beginTransaction().replace(R.id.frame_container,fragment).commit();
  148. mDrawerList.setItemChecked(position, true);
  149. mDrawerList.setSelection(position);
  150. setTitle(navMenuTitles[position]);
  151. mDrawerLayout.closeDrawer(mDrawerList);
  152. } else {
  153. Log.e(“this is mainActivity”, “Error in else case”);
  154. }
  155. }
  156. @Override
  157. public void setTitle(CharSequence title) {
  158. mTitle = title;
  159. getActionBar().setTitle(mTitle);
  160. }
  161. @Override
  162. protected void onPostCreate(Bundle savedInstanceState) {
  163. super.onPostCreate(savedInstanceState);
  164. mDrawerToggle.syncState();
  165. }
  166. @Override
  167. public void onConfigurationChanged(Configuration newConfig) {
  168. super.onConfigurationChanged(newConfig);
  169. mDrawerToggle.onConfigurationChanged(newConfig);
  170. }
  171. }

sliding menu navigation drawer sample
NavigationDrawerCode_V_1.0

  • Sama Gnaneshwar Reddy

    can you please explain,how to set activity for each sidebar menu component

  • S E Bilal Maqbool

    nice post
    but it is better to read code from original source than form here 😛

    • http://www.vizteck.com Barkan Saeed

      Bilal.. Kindly share if you think this is copied

Never Miss an Update


Email address
Get great contents delivered straight to your inbox everyday