Creating Side Menu Navigation Drawer in Android

June 6, 2013
By

Navigation drawer is a UI design pattern that provides a set of menu items when user swipes from left edge of the application to the right. In Android, navigation drawer is available via Android Support library from revision 13 ( May/2013 ) onwards .

An extension to this article which displays icons and counter in the menu items is available in the article titled “Android Sidebar Navigation Drawer with Icons“.  It also supports Android API Level 8 and above.



A nice Android application where navigation drawer is integrated is YouTube.

In this article, we are going to develop an Android application that contains a navigation drawer.

This application is developed in Eclipse (4.2.1) with ADT plugin (22.0.1) and Android SDK (22.0.1) .



1. Create a new Android application project namely “NavigationDrawerDemo”

Creating new Android application project

Figure 1 : Creating new Android application project


2. Configure the application project

Configure the application project

Figure 2 : Configure the application project


3. Design application launcher icon

Design application launcher icon

Figure 3 : Design application launcher icon


4. Create a blank activity

Create a blank activity

Figure 4 : Create a blank activity


5. Enter MainActivity details

Enter MainActivity details

Figure 5 : Enter MainActivity details


6. Add Android Support library to this project

By default, Android support library (android-support-v4.jar ) is added to this project by Eclipse IDE to the directory libs. If it is not added, we can do it manually by doing the following steps :

  • Open Project Explorer by Clicking “Window -> Show View -> Project Explorer”
  • Right click this project
  • Then from popup menu, Click “Android Tools -> Add Support Library “

7. Download and extract the given below file to res/drawable-mdpi


8. Download and extract the given below file to res/drawable-hdpi


9. Download and extract the given below file to res/drawable-xhdpi


10. Update the file res/values/strings.xml


<?xml version="1.0" encoding="utf-8"?>
<resources>

    <string name="app_name">NavigationDrawerDemo</string>
    <string name="action_settings">Settings</string>
    <string name="hello_world">Hello world!</string>
    <string-array name="rivers">
        <item >Brahmaputra</item>
        <item >Ganges</item>
        <item >Kaveri</item>
        <item >Godavari</item>
        <item >Periyar</item>
        <item >Bharathappuzha (Nila)</item>
        <item >Yamuna</item>
    </string-array>
    <string name="drawer_open">Open navigation drawer</string>
    <string name="drawer_close">Close navigation drawer</string>

</resources>


11. Update the layout file res/layout/activity_main.xml


<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">
    <!-- The main content view -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />
    <!-- The navigation drawer -->
    <ListView android:id="@+id/drawer_list"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp"
        android:background="#111"/>
</android.support.v4.widget.DrawerLayout>


12. Create the layout file res/layout/fragment_layout.xml


<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/tv_content"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"
        android:textSize="40sp" />

</LinearLayout>


13. Create the layout file res/layout/drawer_list_item.xml


<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:textAppearance="?android:attr/textAppearanceListItemSmall"
    android:gravity="center_vertical"
    android:paddingLeft="16dp"
    android:paddingRight="16dp"
    android:textColor="#fff"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:minHeight="?android:attr/listPreferredItemHeightSmall"/>


14. Create the fragment class src/in/wptrafficanalyzer/navigationdrawerdemo/RiverFragment.java


package in.wptrafficanalyzer.navigationdrawerdemo;

import android.app.Fragment;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

public class RiverFragment extends Fragment{

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

        // Retrieving the currently selected item number
        int position = getArguments().getInt("position");

        // List of rivers
        String[] rivers = getResources().getStringArray(R.array.rivers);

        // Creating view correspoding to the fragment
        View v = inflater.inflate(R.layout.fragment_layout, container, false);

        // Getting reference to the TextView of the Fragment
        TextView tv = (TextView) v.findViewById(R.id.tv_content);

        // Setting currently selected river name in the TextView
        tv.setText(rivers[position]);

        // Updating the action bar title
        getActivity().getActionBar().setTitle(rivers[position]);

        return v;
    }
}


15. Update the class src/in/wptrafficanalyzer/navigationdrawerdemo/MainActivity.java


package in.wptrafficanalyzer.navigationdrawerdemo;

import android.app.Activity;
import android.app.FragmentManager;
import android.app.FragmentTransaction;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.ListView;

public class MainActivity extends Activity {

    // Within which the entire activity is enclosed
    DrawerLayout mDrawerLayout;

    // ListView represents Navigation Drawer
    ListView mDrawerList;

    // ActionBarDrawerToggle indicates the presence of Navigation Drawer in the action bar
    ActionBarDrawerToggle mDrawerToggle;

    // Title of the action bar
    String mTitle="";

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        mTitle = (String) getTitle();

        // Getting reference to the DrawerLayout
        mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

        mDrawerList = (ListView) findViewById(R.id.drawer_list);

        // Getting reference to the ActionBarDrawerToggle
        mDrawerToggle = new ActionBarDrawerToggle( this,
            mDrawerLayout,
            R.drawable.ic_drawer,
            R.string.drawer_open,
            R.string.drawer_close){

                /** Called when drawer is closed */
                public void onDrawerClosed(View view) {
                    getActionBar().setTitle(mTitle);
                    invalidateOptionsMenu();
                }

                /** Called when a drawer is opened */
                public void onDrawerOpened(View drawerView) {
                    getActionBar().setTitle("Select a river");
                    invalidateOptionsMenu();
                }
        };

        // Setting DrawerToggle on DrawerLayout
        mDrawerLayout.setDrawerListener(mDrawerToggle);

        // Creating an ArrayAdapter to add items to the listview mDrawerList
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(
            getBaseContext(),
            R.layout.drawer_list_item ,
            getResources().getStringArray(R.array.rivers)
        );

        // Setting the adapter on mDrawerList
        mDrawerList.setAdapter(adapter);

        // Enabling Home button
        getActionBar().setHomeButtonEnabled(true);

        // Enabling Up navigation
        getActionBar().setDisplayHomeAsUpEnabled(true);

        // Setting item click listener for the listview mDrawerList
        mDrawerList.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent,
                View view,
                int position,
                long id) {

                    // Getting an array of rivers
                    String[] rivers = getResources().getStringArray(R.array.rivers);

                    //Currently selected river
                    mTitle = rivers[position];

                    // Creating a fragment object
                    RiverFragment rFragment = new RiverFragment();

                    // Creating a Bundle object
                    Bundle data = new Bundle();

                    // Setting the index of the currently selected item of mDrawerList
                    data.putInt("position", position);

                    // Setting the position to the fragment
                    rFragment.setArguments(data);

                    // Getting reference to the FragmentManager
                    FragmentManager fragmentManager = getFragmentManager();

                    // Creating a fragment transaction
                    FragmentTransaction ft = fragmentManager.beginTransaction();

                    // Adding a fragment to the fragment transaction
                    ft.replace(R.id.content_frame, rFragment);

                    // Committing the transaction
                    ft.commit();

                    // Closing the drawer
                    mDrawerLayout.closeDrawer(mDrawerList);
            }
        });
    }

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

    /** Handling the touch event of app icon */
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        if (mDrawerToggle.onOptionsItemSelected(item)) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

    /** Called whenever we call invalidateOptionsMenu() */
    @Override
    public boolean onPrepareOptionsMenu(Menu menu) {
        // If the drawer is open, hide action items related to the content view
        boolean drawerOpen = mDrawerLayout.isDrawerOpen(mDrawerList);

        menu.findItem(R.id.action_settings).setVisible(!drawerOpen);
        return super.onPrepareOptionsMenu(menu);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
}


16. Update the menu file res/menu/main.xml

<menu xmlns:android="http://schemas.android.com/apk/res/android" >
    <item
        android:id="@+id/action_settings"
        android:orderInCategory="100"
        android:showAsAction="ifRoom"
        android:title="@string/action_settings"/>
    </menu>

17. Screenshots of the running application

Selecting an item from the side menu

Figure 6 : Selecting an item from the side menu

Showing the screen corresponding to the selected menu item

Figure 7 : Showing the screen corresponding to the selected menu item


18. Download source code


19. Reference

http://developer.android.com/training/implementing-navigation/nav-drawer.html


How to hire me?

I am George Mathew, working as software architect and Android app developer at wptrafficanalyzer.in

You can hire me on hourly basis or on project basis for Android applications development.

For hiring me, please mail your requirements to info@wptrafficanalyzer.in.

My other blogs
store4js.blogspot.com


Android Knowledge Quiz

Ready to test your knowledge in Android? Take this quiz :



Tags: , , ,

24 Responses to Creating Side Menu Navigation Drawer in Android

  1. sajadpm on July 24, 2013 at 12:54 pm

    hi , thanks for very good tutorial but can i use with actionbar sherlock ?

  2. George on August 23, 2013 at 10:27 pm

    Thanks for tutorial! I tried this, it works fine on emulator but not running on mobile can you please suggest
    Thanks…!

  3. Shingi on September 24, 2013 at 4:51 pm

    awesome ,it works. may i have code for the same app but supporting api version 9 and above

  4. Marco on September 28, 2013 at 5:28 pm

    Hi, thanks for your tutorial!
    One question: How to Add icons in navigation drawer menu?

  5. chandu on December 2, 2013 at 10:32 am

    hey i like this example and i want drawer layout without action bar and slider is on both sides like face book navigation one side menu and side notifications

    plz
    waiting for that

  6. Ana-Maria on December 9, 2013 at 2:12 am

    Thanks for the tutorial. It was really useful.
    I am writing to ask you for help.
    When i click on one river i want the next window to show me some details about the lake (which i introduce) and not its name.
    I tried to modify the onOptionsItemSelected() using a swith but it is not working.
    switch(item.getItemId()) {
    case R.array.rivers:
    ..}

  7. Rahul on January 3, 2014 at 10:45 am

    Very nice tutorial, neatly explained…Thank you very much for such tutorial but I have query How to place ActionBarDrawerToggle at the bottom or How to customize Drawer opening and closing on custom image button?

  8. Sathish on January 3, 2014 at 11:39 am

    Hi george thanks for tutorial ,i have a doubt can we use side navigation menu in tab layout , if yes send me the codings.If its not possible send me some other solution……

  9. Sagar on October 16, 2014 at 7:04 pm

    Thanks …..its very useful tutorial for the android fresher.

  10. George on December 16, 2014 at 1:16 am

    How can I add data for every item in the navigation drawer.

  11. Arpit rathod on December 17, 2014 at 5:43 pm

    very nice tutorial…bt how to add listview inside fragment…(list view in RiverFragment.java)

  12. pratik on January 3, 2015 at 10:44 pm

    how do add this side menu in other activity or other pages

  13. Waseem Akram on February 23, 2015 at 12:30 pm

    plz tell me how to add slider on a screen and some image view in same activity

  14. Cuckoo on April 24, 2015 at 3:29 pm

    Can u please help me with setting background color to my side menu item when it is clicked.the color should stay as long as i select another item in the list.i really don’t know how to do this.please help me.thanks

  15. sandeep on May 14, 2015 at 1:21 pm

    Hey thank you, its working fine, I have to implement on my exisitng app, it already have a activity_main.xml with components with slidingtablayout. How can I add navigation drawer on the existing layout? PLease help

  16. gagan on June 3, 2015 at 5:05 pm

    I have created a sample maps v2 app. I am trying to add a drawer to the same but not able to get that to work. Could you please provide some example code for that.
    ps: i am new to android development.

  17. adi on September 3, 2015 at 8:49 pm

    Thanks
    It very helpful

  18. Krishna on September 7, 2015 at 9:13 pm

    Hi Nice to see your Tutorial, Reply me your Hourly Price so that we can work together.

  19. Rohit Pitre on September 28, 2015 at 12:31 pm

    Really nice tutorial. very helpful.. Thank you

  20. Sayana Ramesh on November 5, 2015 at 11:29 am

    Hi sir,Thanks for the tutorial,it was very useful

  21. Felipe on November 12, 2015 at 5:28 am

    how can I use the drawer layout image on the main screen , because when I put ImageView from the home screen to select an item in the drawer listview shows blank screen.

  22. mojtaba on June 10, 2016 at 7:10 pm

    Hi,how can i make Side Menu Navigation right to left?

  23. vittu on June 27, 2016 at 7:06 pm

    sir i want to add an button in navigation drawer activity which launch another activity

    for example i create a home activity i want to add more than 5 button in home activity which will be launch another activity please help me to solve this problem

Leave a Reply

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

Be friend at g+

Subscribe for Lastest Updates

FBFPowered by ®Google Feedburner