Android has different navigation options  available to navigate between views in an android application. Navigation drawer is the the one of the best option out of them. In this tutorial I’ll try to demonstrate how implement a navigation drawer according to your customizations. If look at the navigation drawer sample application at developer.android.com website, you can see it is a listview  used to navigate through different fragments. As you can see  in the below screenshot it simply list down the names of different planets and when we click on a single item it will close the navigation drawer and it will load an image of that planet.

Navigation Drawer Sample App Navigation
Navigation Drawer Sample App Navigation

Most of the google apps use navigation drawer. But those navigation drawers are customized by developers according to application requirement and usability. But android developer guide will not show you how to customize the navigation drawer according to users need. See below image to get an idea about custom navigation drawers.

Example Custom Navigation Drawer Apps
Example Custom Navigation Drawer Apps

In this tutorial I’ll show you how to create a custom navigation drawer. First part of this tutorial I’ll cover the basic implementation  of navigation drawer from second part onwards I’ll show you how to customize it.If you know basic implementation then skip this part and refer the customization part. You can find source code and video demonstration of this tutorial at end of this page.

Demo Video

Basic Implementation of Navigation Drawer

Step 1 : Download Resources

Before you start you need to download below resources.

Resource Pack : Download the Resource Pack

Now extract the “NavigationDrawer_ResourcePack.zip” file you download.

Step 2 : Create a Project and Setup the Project

Create a new android project. Give the  Application Name as “NavigationDrawer“, Package Name as “com.tutecentral.navigationdrawer”  and select the Minimum Required SDK as “API 14: Android 4.0 (ICS)“. I’ll keep the Activity Name as “MainActivity” and Layout Name as “activity_main“.

Copy and paste all drawable files in “NavigationDrawer_ResourcePack -> app_drawables” folder into application drawables. Now we done with project setup. 

Step 3 : Create Layout Files and Fragment

For demonstration purposes I’ll use three fragments to navigate between navigation drawer items. Okay Now create four layout files respectively “custom_drawer_item“, “fragment_layout_one“, “fragment_layout_two” and “fragment_layout_three“.  “custom_drawer_item” is used for build a custom listview and other three fragment layout used for Fragment Views. 

[quote_box_center]

Steps to Create a New Layout File.

  1. Right Click on the “res -> layout” folder
  2. Go to “New -> Android XML File
  3. Select the Resource Type as “Layout
  4. Give a File Name
  5. Select the Root Element (Most of the time it is a Layout type)
  6. Click “Finish” button

[/quote_box_center]

Open  “activity_main.xml” file in “res->layout” folder. Copy and paste below code into activity_main.xml layout file. Dont forget to add the v4 support library (android-support-v4.jar) to lib folder in the project.

<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">

    <!-- As the main content view, the view below consumes the entire
         space available using match_parent in both dimensions. -->
    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <!-- android:layout_gravity="start" tells DrawerLayout to treat
         this as a sliding drawer on the left side for left-to-right
         languages and on the right side for right-to-left languages.
         The drawer is given a fixed width in dp and extends the full height of
         the container. A solid background is used for contrast
         with the content view. -->

    <ListView
        android:id="@+id/left_drawer"
        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="#ffff"/>
</android.support.v4.widget.DrawerLayout>
[quote_box_center]

Steps to Add Support Library to Application

  1. Goto Following Path “Your Android SDK Drive” \sdk\extras\android\support\v4
  2. Copy “android-support-v4.jar” file
  3. Paste it in “lib” folder in your application
[/quote_box_center]

Now copy and paste the below xml to “custom_drawer_item.xml” layout file. Be aware this xml file will be change when we creating a custom navigation  drawer

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

    <LinearLayout
      android:id="@+id/itemLayout"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content"
      android:layout_alignParentLeft="true"
      android:orientation="vertical"

      android:layout_marginTop="0dp"
      android:background="?android:attr/activatedBackgroundIndicator"
     >

              <LinearLayout

                  android:layout_width="fill_parent"
                  android:layout_height="wrap_content"
                  android:minHeight="55dp"
                 >

                  <ImageView
                      android:id="@+id/drawer_icon"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      />

                  <TextView
                      android:id="@+id/drawer_itemName"
                      android:layout_width="wrap_content"
                      android:layout_height="wrap_content"
                      android:textAppearance="?android:attr/textAppearanceLarge"

                       />
              </LinearLayout>

               <View
      android:layout_width="match_parent"
      android:layout_height="1dp"
      android:layout_marginBottom="1dp"
      android:layout_marginTop="1dp"
      android:layout_marginLeft="10dp"
      android:layout_marginRight="10dp"
      android:background="#DADADC"

       ></View>

    </LinearLayout>

</RelativeLayout>

Now copy and paste the below xml code to all three fragment xml files. Dont forget to change the id attribute values in other two layout file. See the comment in the code.

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

    <!--
    **************************IMPORTANT***********************************
     change this id attribute values as "frag2_icon" and "frag2_text" for
     fragment_layout_two.xml and "frag3_icon" and "frag3_text" for
     fragment_layout_three.xml
    **********************************************************************
      -->

    <ImageView
        android:id="@+id/frag1_icon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
      />

    <TextView
        android:id="@+id/frag1_text"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="10dp"
        android:textAppearance="?android:attr/textAppearanceLarge" />

</LinearLayout>

Next add following item to “strings.xml”  file in “res-> values” folder

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

Now we are done with xml files.

Step 4 : Create Fragment Class and Custom ListView Adapter

Next task is to create fragment class for all three layout files and implement a custom listview adapter.  Create five class list down below

  • CustomDrawerAdapter
  • DrawerItem
  • FragmentOne
  • FragmentTwo
  • FragmentThree
[quote_box_center]

Steps to Create a New Class File.

  1. Right Click on the “src-> com.tutecentral.navigationdrawer” package
  2. Go to “New -> Class
  3. Give a Class Name
  4. Click “Finish” button
[/quote_box_center]

Copy and paste below codes to FragmentOne, FragmentTwo and FragmentThree class respectively. All these class are subclass of Fragment Class

package com.tutecentral.navigationdrawer;

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

public class FragmentOne extends Fragment {

	ImageView ivIcon;
	TextView tvItemName;

	public static final String IMAGE_RESOURCE_ID = "iconResourceID";
	public static final String ITEM_NAME = "itemName";

	public FragmentOne() {

	}

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

		View view = inflater.inflate(R.layout.fragment_layout_one, container,
				false);

		ivIcon = (ImageView) view.findViewById(R.id.frag1_icon);
		tvItemName = (TextView) view.findViewById(R.id.frag1_text);

		tvItemName.setText(getArguments().getString(ITEM_NAME));
		ivIcon.setImageDrawable(view.getResources().getDrawable(
				getArguments().getInt(IMAGE_RESOURCE_ID)));
		return view;
	}

}
package com.tutecentral.navigationdrawer;

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

public class FragmentTwo   extends Fragment {

	ImageView ivIcon;
	TextView tvItemName;

	public static final String IMAGE_RESOURCE_ID = "iconResourceID";
	public static final String ITEM_NAME = "itemName";

	public FragmentTwo()
	{

	}

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

		View view=inflater.inflate(R.layout.fragment_layout_two,container, false);

		ivIcon=(ImageView)view.findViewById(R.id.frag2_icon);
		tvItemName=(TextView)view.findViewById(R.id.frag2_text);

		tvItemName.setText(getArguments().getString(ITEM_NAME));
		ivIcon.setImageDrawable(view.getResources().getDrawable(
				getArguments().getInt(IMAGE_RESOURCE_ID)));
		return view;
	}

}
package com.tutecentral.navigationdrawer;

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

public class FragmentThree extends Fragment {

	ImageView ivIcon;
	TextView tvItemName;

	public static final String IMAGE_RESOURCE_ID = "iconResourceID";
	public static final String ITEM_NAME = "itemName";

	public FragmentThree() {

	}

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

		View view = inflater.inflate(R.layout.fragment_layout_three, container,
				false);

		ivIcon = (ImageView) view.findViewById(R.id.frag3_icon);
		tvItemName = (TextView) view.findViewById(R.id.frag3_text);

		tvItemName.setText(getArguments().getString(ITEM_NAME));
		ivIcon.setImageDrawable(view.getResources().getDrawable(
				getArguments().getInt(IMAGE_RESOURCE_ID)));
		return view;
	}

}

Next open the “DrawerItem.java” class and update it as below code. This class also be upgrade when creating the custom navigation drawer

package com.tutecentral.navigationdrawer;

public class DrawerItem {

	String ItemName;
	int imgResID;

	public DrawerItem(String itemName, int imgResID) {
		super();
		ItemName = itemName;
		this.imgResID = imgResID;
	}

	public String getItemName() {
		return ItemName;
	}
	public void setItemName(String itemName) {
		ItemName = itemName;
	}
	public int getImgResID() {
		return imgResID;
	}
	public void setImgResID(int imgResID) {
		this.imgResID = imgResID;
	}

}

Now we can create a custom adapter for drawer listview. Open the “CustomDrawerAdapter.java” class and update the class according to below code. Keep in mind class will be update when customizing the navigation drawer.

package com.tutecentral.navigationdrawer;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomDrawerAdapter extends ArrayAdapter<DrawerItem> {

	Context context;
	List<DrawerItem> drawerItemList;
	int layoutResID;

	public CustomDrawerAdapter(Context context, int layoutResourceID,
			List<DrawerItem> listItems) {
		super(context, layoutResourceID, listItems);
		this.context = context;
		this.drawerItemList = listItems;
		this.layoutResID = layoutResourceID;

	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		DrawerItemHolder drawerHolder;
		View view = convertView;

		if (view == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			drawerHolder = new DrawerItemHolder();

			view = inflater.inflate(layoutResID, parent, false);
			drawerHolder.ItemName = (TextView) view
					.findViewById(R.id.drawer_itemName);
			drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);

			view.setTag(drawerHolder);

		} else {
			drawerHolder = (DrawerItemHolder) view.getTag();

		}

		DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);

		drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(
				dItem.getImgResID()));
		drawerHolder.ItemName.setText(dItem.getItemName());

		return view;
	}

	private static class DrawerItemHolder {
		TextView ItemName;
		ImageView icon;
	}
}

Okay we are done with the adapter class now we need to update the “MainActivity.java” class. This class I’ll update step by step so you can understand how it works.  Open the MainActivity.java class.

First declare the below objects.

public class MainActivity extends Activity {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;

	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	CustomDrawerAdapter adapter;

	List<DrawerItem> dataList;
...// dont copy this line

Now initialize the declared object in onCreate() method

...
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Initializing
		dataList = new ArrayList<DrawerItem>();
		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);

		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);
...

Now add item to the “dataList” object. So those list items will display in the drawer

// Add Drawer Item to dataList
		// Add Drawer Item to dataList
		dataList.add(new DrawerItem("Message", R.drawable.ic_action_email));
		dataList.add(new DrawerItem("Likes", R.drawable.ic_action_good));
		dataList.add(new DrawerItem("Games", R.drawable.ic_action_gamepad));
		dataList.add(new DrawerItem("Lables", R.drawable.ic_action_labels));
		dataList.add(new DrawerItem("Search", R.drawable.ic_action_search));
		dataList.add(new DrawerItem("Cloud", R.drawable.ic_action_cloud));
		dataList.add(new DrawerItem("Camara", R.drawable.ic_action_camera));
		dataList.add(new DrawerItem("Video", R.drawable.ic_action_video));
		dataList.add(new DrawerItem("Groups", R.drawable.ic_action_group));
		dataList.add(new DrawerItem("Import & Export",
				R.drawable.ic_action_import_export));
		dataList.add(new DrawerItem("About", R.drawable.ic_action_about));
		dataList.add(new DrawerItem("Settings", R.drawable.ic_action_settings));
		dataList.add(new DrawerItem("Help", R.drawable.ic_action_help));
...

Now initialize and set the adapter to the  drawer listview

...
		adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
				dataList);

		mDrawerList.setAdapter(adapter);
...

Now create a method in MainActivity.java to select the correct fragment. I’ll call this method “SelectItem()” which will take a one integer parameter, to identify the position of the selected item. In this method I’ll use a “switch-case” statement to get correct fragment. I created only three fragments for demonstration purpose. You can do this even using a single fragment class.

public void SelectItem(int possition) {

		Fragment fragment = null;
		Bundle args = new Bundle();
		switch (possition) {
		case 0:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 1:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 2:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 3:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 4:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 5:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 6:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 7:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 8:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 9:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 10:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 11:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 12:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		default:
			break;
		}

		fragment.setArguments(args);
		FragmentManager frgManager = getFragmentManager();
		frgManager.beginTransaction().replace(R.id.content_frame, fragment)
				.commit();

		mDrawerList.setItemChecked(possition, true);
		setTitle(dataList.get(possition).getItemName());
		mDrawerLayout.closeDrawer(mDrawerList);

	}

Now you need to override following methods and update those methods as following code

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

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

      @Override
      public boolean onOptionsItemSelected(MenuItem item) {
            // The action bar home/up action should open or close the drawer.
            // ActionBarDrawerToggle will take care of this.
            if (mDrawerToggle.onOptionsItemSelected(item)) {
                  return true;
            }

            return false;
      }

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggles
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

Now we need to create custom “OnItemClickListener“. To do that create a another class called “DrawerItemClickListener” inside MainActivity.java.  “DrawerItemClickListener” class implements the  “OnItemClickListener“. 

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

		}
	}

Now came back to OnCreate() method and set the OnItemClickListener as below

	mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

Now we need to enable the HomeUpButton for action bar and set the toggle to the Drawer Layout

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

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};

		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			SelectItem(0);
		}

Now our MainActivity.java class is completed. Below you can see the complete code for MainActivity.java class

package com.tutecentral.navigationdrawer;

import java.util.ArrayList;
import java.util.List;

import android.os.Bundle;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.res.Configuration;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.view.GravityCompat;
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.ListView;

public class MainActivity extends Activity {

	private DrawerLayout mDrawerLayout;
	private ListView mDrawerList;
	private ActionBarDrawerToggle mDrawerToggle;

	private CharSequence mDrawerTitle;
	private CharSequence mTitle;
	CustomDrawerAdapter adapter;

	List<DrawerItem> dataList;

	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);

		// Initializing
		dataList = new ArrayList<DrawerItem>();
		mTitle = mDrawerTitle = getTitle();
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);
		mDrawerList = (ListView) findViewById(R.id.left_drawer);

		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);

		// Add Drawer Item to dataList
		dataList.add(new DrawerItem("Message", R.drawable.ic_action_email));
		dataList.add(new DrawerItem("Likes", R.drawable.ic_action_good));
		dataList.add(new DrawerItem("Games", R.drawable.ic_action_gamepad));
		dataList.add(new DrawerItem("Lables", R.drawable.ic_action_labels));
		dataList.add(new DrawerItem("Search", R.drawable.ic_action_search));
		dataList.add(new DrawerItem("Cloud", R.drawable.ic_action_cloud));
		dataList.add(new DrawerItem("Camara", R.drawable.ic_action_camera));
		dataList.add(new DrawerItem("Video", R.drawable.ic_action_video));
		dataList.add(new DrawerItem("Groups", R.drawable.ic_action_group));
		dataList.add(new DrawerItem("Import & Export",
				R.drawable.ic_action_import_export));
		dataList.add(new DrawerItem("About", R.drawable.ic_action_about));
		dataList.add(new DrawerItem("Settings", R.drawable.ic_action_settings));
		dataList.add(new DrawerItem("Help", R.drawable.ic_action_help));

		adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,
				dataList);

		mDrawerList.setAdapter(adapter);

		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

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

		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {
			public void onDrawerClosed(View view) {
				getActionBar().setTitle(mTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}

			public void onDrawerOpened(View drawerView) {
				getActionBar().setTitle(mDrawerTitle);
				invalidateOptionsMenu(); // creates call to
											// onPrepareOptionsMenu()
			}
		};

		mDrawerLayout.setDrawerListener(mDrawerToggle);

		if (savedInstanceState == null) {
			SelectItem(0);
		}

	}

	@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;
	}

	public void SelectItem(int possition) {

		Fragment fragment = null;
		Bundle args = new Bundle();
		switch (possition) {
		case 0:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 1:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 2:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 3:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 4:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 5:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 6:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 7:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 8:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 9:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 10:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 11:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 12:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		default:
			break;
		}

		fragment.setArguments(args);
		FragmentManager frgManager = getFragmentManager();
		frgManager.beginTransaction().replace(R.id.content_frame, fragment)
				.commit();

		mDrawerList.setItemChecked(possition, true);
		setTitle(dataList.get(possition).getItemName());
		mDrawerLayout.closeDrawer(mDrawerList);

	}

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

	@Override
	protected void onPostCreate(Bundle savedInstanceState) {
		super.onPostCreate(savedInstanceState);
		// Sync the toggle state after onRestoreInstanceState has occurred.
		mDrawerToggle.syncState();
	}

	@Override
	public void onConfigurationChanged(Configuration newConfig) {
		super.onConfigurationChanged(newConfig);
		// Pass any configuration change to the drawer toggles
		mDrawerToggle.onConfigurationChanged(newConfig);
	}

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {
		// The action bar home/up action should open or close the drawer.
		// ActionBarDrawerToggle will take care of this.
		if (mDrawerToggle.onOptionsItemSelected(item)) {
			return true;
		}

		return false;
	}

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

		}
	}

}

Now we are done with the “Basic Implementation of Navigation Drawer”  you can run this application now to see the output of the basic drawer.

Basic Navigation Drawer
Basic Navigation Drawer

You can download the basic navigation drawer sample code at end of this tutorial.

Customizing the Navigation Drawer

Now we can update this basic implementation of navigation drawer  to more customized navigation drawer. As I mention  we have to update existing class  and xml layouts to do this. I’ll customize the navigation drawer by adding a SpinnerView to select the user account and add some headers to the  listview to categorize the list items (like youtube app).

Step 5 : Creating Custom Spinner View

Create a xml layout called “custom_spinner_item”  file in “res->layout“. Add the following xml code to the layout file. This is the layout file passed to the custom spinner adapter.

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <ImageView
        android:id="@+id/left_pic"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="5dp" />

    <TextView
        android:id="@+id/text_main_name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginLeft="5dp"
        android:layout_marginTop="0dp"
        android:layout_toRightOf="@+id/left_pic"
        android:padding="0dp"
        android:textAppearance="?android:attr/textAppearanceMedium"
        android:textColor="#1d97dd"
        android:textStyle="bold" />

    <TextView
        android:id="@+id/sub_text_email"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@+id/text_main_name"
        android:layout_marginLeft="5dip"
        android:layout_toRightOf="@+id/left_pic"
        android:textAppearance="?android:attr/textAppearanceSmall"
        android:textColor="#777777" />

</RelativeLayout>

Now create below two class for custom adapter and layout model

  • CustomSpinnerAdapter
  • SpinnerItem

Now open the SpinnerItem.java and add the below code to the class file.

package com.tutecentral.navigationdrawer;

public class SpinnerItem {

	int drawableResID;
	String name;
	String email;

	public SpinnerItem(int drawableResID, String name, String email) {
		super();
		this.drawableResID = drawableResID;
		this.name = name;
		this.email = email;
	}

	public int getDrawableResID() {
		return drawableResID;
	}
	public void setDrawableResID(int drawableResID) {
		this.drawableResID = drawableResID;
	}
	public String getName() {
		return name;
	}
	public void setName(String name) {
		this.name = name;
	}
	public String getEmail() {
		return email;
	}
	public void setEmail(String email) {
		this.email = email;
	}

}

Now you can use this class to create a spinner custom adapter. So open the  “CustomSpinnerAdapter.java” class and update the class according to below cording

package com.tutecentral.navigationdrawer;

import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class CustomSpinnerAdapter extends ArrayAdapter<SpinnerItem>{

	public CustomSpinnerAdapter(Context context, int layoutResourceID,
			int textViewResourceId, List<SpinnerItem> spinnerDataList) {
		super(context, layoutResourceID, textViewResourceId, spinnerDataList);

		this.context=context;
		this.layoutResID=layoutResourceID;
		this.spinnerData=spinnerDataList;

	}

	Context context;
	int layoutResID;
	List<SpinnerItem> spinnerData;

	public CustomSpinnerAdapter(Context context, int layoutResourceID,
			List<SpinnerItem> spinnerDataList) {
		super(context, layoutResourceID, spinnerDataList);

		this.context=context;
		this.layoutResID=layoutResourceID;
		this.spinnerData=spinnerDataList;

	}

	@Override
	public View getDropDownView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		return getCustomView(position, convertView, parent);
	}

	@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub
		return getCustomView(position, convertView, parent);
	}

	public View getCustomView(int position, View convertView, ViewGroup parent) {

		View row=convertView;
		SpinnerHolder holder;

		if(row==null)
		{
			LayoutInflater inflater=((Activity)context).getLayoutInflater();

			row=inflater.inflate(layoutResID, parent, false);
			holder=new SpinnerHolder();

			holder.userImage=(ImageView)row.findViewById(R.id.left_pic);
			holder.name=(TextView)row.findViewById(R.id.text_main_name);
			holder.email=(TextView)row.findViewById(R.id.sub_text_email);

			row.setTag(holder);
		}
		else
		{
			holder=(SpinnerHolder)row.getTag();

		}

		SpinnerItem spinnerItem=spinnerData.get(position);

		holder.userImage.setImageDrawable(row.getResources().getDrawable(spinnerItem.getDrawableResID()));
		holder.name.setText(spinnerItem.getName());
		holder.email.setText(spinnerItem.getEmail());

		return row;

	}

	private static class SpinnerHolder
	{
		ImageView userImage;
		TextView  name,email;

	}

}

Now we are completed the “CustomSpinnerAdapter.java” class. We can use this class in “CustomDrawerAdapter.java” to populate a spinner in the navigation drawer.

Next  update the “custom_drawer_item.xml” layout file. See the below code and update your xml file.To update replace the old xml code by below updated code.

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

     <LinearLayout
        android:id="@+id/spinnerLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
     	android:layout_marginTop="0dp"
         >

           <Spinner
		            android:id="@+id/drawerSpinner"
		            android:layout_width="fill_parent"
		            android:layout_height="0dp"
		            android:layout_weight="1" />
    </LinearLayout>

    <LinearLayout
        android:id="@+id/headerLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical"
     	android:layout_marginTop="20dp"
         >

        <TextView
            android:id="@+id/drawerTitle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"

            android:textAppearance="?android:attr/textAppearanceSmall" />

             <View
        android:layout_width="match_parent"
        android:layout_height="2dp"
        android:layout_marginBottom="1dp"
        android:layout_marginTop="1dp"
        android:background="#DADADC" ></View>

    </LinearLayout>

      <LinearLayout
        android:id="@+id/itemLayout"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:orientation="vertical"
        android:layout_marginTop="0dp"

        android:background="?android:attr/activatedBackgroundIndicator"
       >

		    <LinearLayout

		        android:layout_width="fill_parent"
		        android:layout_height="wrap_content"
		        android:minHeight="50dp"
		       >

		        <ImageView
		            android:id="@+id/drawer_icon"
		            android:layout_width="wrap_content"
		            android:layout_height="wrap_content"
		            />

		        <TextView
		            android:id="@+id/drawer_itemName"
		            android:layout_width="wrap_content"
		            android:layout_height="wrap_content"
		            android:textAppearance="?android:attr/textAppearanceLarge"

		             />
		    </LinearLayout>

		     <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:layout_marginBottom="0dp"
        android:layout_marginTop="0dp"
        android:layout_marginLeft="10dp"
        android:layout_marginRight="10dp"
        android:background="#DADADC"
         ></View>

      </LinearLayout>
</RelativeLayout>

Now we can do updates for other class used to create navigation drawer.

1. Updates For “DrawerItem.java” class

public class DrawerItem {

	String ItemName;
	int imgResID;
	String title;
	boolean isSpinner;

...
        public DrawerItem(boolean isSpinner) {
		this(null, 0);
		this.isSpinner = isSpinner;
	}

	public DrawerItem(String title) {
		this(null, 0);
		this.title = title;
	}

...
	public String getTitle() {
		return title;
	}
	public void setTitle(String title) {
		this.title = title;
	}

	public boolean isSpinner() {
		return isSpinner;
	}
...
}

2. Updates for CustomDrawerAdapter.java Class

In this class changes will only happens to getView() method & DrawerItemHolder internal class. Just copy and replace the below code to the class file so you may not get any errors while updating.

@Override
	public View getView(int position, View convertView, ViewGroup parent) {
		// TODO Auto-generated method stub

		DrawerItemHolder drawerHolder;
		View view = convertView;

		if (view == null) {
			LayoutInflater inflater = ((Activity) context).getLayoutInflater();
			drawerHolder = new DrawerItemHolder();

			view = inflater.inflate(layoutResID, parent, false);
			drawerHolder.ItemName = (TextView) view
					.findViewById(R.id.drawer_itemName);
			drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);

			drawerHolder.spinner = (Spinner) view
					.findViewById(R.id.drawerSpinner);

			drawerHolder.title = (TextView) view.findViewById(R.id.drawerTitle);

			drawerHolder.headerLayout = (LinearLayout) view
					.findViewById(R.id.headerLayout);
			drawerHolder.itemLayout = (LinearLayout) view
					.findViewById(R.id.itemLayout);
			drawerHolder.spinnerLayout = (LinearLayout) view
					.findViewById(R.id.spinnerLayout);

			view.setTag(drawerHolder);

		} else {
			drawerHolder = (DrawerItemHolder) view.getTag();

		}

		DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);

		if (dItem.isSpinner()) {
			drawerHolder.headerLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.itemLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.spinnerLayout.setVisibility(LinearLayout.VISIBLE);

			List<SpinnerItem> userList = new ArrayList<SpinnerItem>();

		        userList.add(new SpinnerItem(R.drawable.user1, "Ahamed Ishak",
					"ishakgmail.com"));

			userList.add(new SpinnerItem(R.drawable.user2, "Brain Jekob",
					"brain.jgmail.com"));

			CustomSpinnerAdapter adapter = new CustomSpinnerAdapter(context,
					R.layout.custom_spinner_item, userList);

			drawerHolder.spinner.setAdapter(adapter);

			drawerHolder.spinner
					.setOnItemSelectedListener(new OnItemSelectedListener() {

						@Override
						public void onItemSelected(AdapterView<?> arg0,
								View arg1, int arg2, long arg3) {

							Toast.makeText(context, "User Changed",
									Toast.LENGTH_SHORT).show();
						}

						@Override
						public void onNothingSelected(AdapterView<?> arg0) {
							// TODO Auto-generated method stub

						}
					});

		} else if (dItem.getTitle() != null) {
			drawerHolder.headerLayout.setVisibility(LinearLayout.VISIBLE);
			drawerHolder.itemLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.spinnerLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.title.setText(dItem.getTitle());

		} else {

			drawerHolder.headerLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.spinnerLayout.setVisibility(LinearLayout.INVISIBLE);
			drawerHolder.itemLayout.setVisibility(LinearLayout.VISIBLE);

			drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(
					dItem.getImgResID()));
			drawerHolder.ItemName.setText(dItem.getItemName());

		}
		return view;
	}

	private static class DrawerItemHolder {
		TextView ItemName, title;
		ImageView icon;
		LinearLayout headerLayout, itemLayout, spinnerLayout;
		Spinner spinner;
	}

3. Updates for MainActivity.java class

In  OnCreate method we need call the correct constructor of the DrawerItem class when we adding item to the dataList object and need to change the if condition  which is used to check “savedInstanceState == null“. See the below coding and update your code.

...
// Add Drawer Item to dataList
		dataList.add(new DrawerItem(true)); // adding a spinner to the list

		dataList.add(new DrawerItem("My Favorites")); // adding a header to the list
		dataList.add(new DrawerItem("Message", R.drawable.ic_action_email));
		dataList.add(new DrawerItem("Likes", R.drawable.ic_action_good));
		dataList.add(new DrawerItem("Games", R.drawable.ic_action_gamepad));
		dataList.add(new DrawerItem("Lables", R.drawable.ic_action_labels));

		 dataList.add(new DrawerItem("Main Options"));// adding a header to the list
		dataList.add(new DrawerItem("Search", R.drawable.ic_action_search));
		dataList.add(new DrawerItem("Cloud", R.drawable.ic_action_cloud));
		dataList.add(new DrawerItem("Camara", R.drawable.ic_action_camera));
		dataList.add(new DrawerItem("Video", R.drawable.ic_action_video));
		dataList.add(new DrawerItem("Groups", R.drawable.ic_action_group));
		dataList.add(new DrawerItem("Import & Export",
				R.drawable.ic_action_import_export));

		 dataList.add(new DrawerItem("Other Option")); // adding a header to the list
		dataList.add(new DrawerItem("About", R.drawable.ic_action_about));
		dataList.add(new DrawerItem("Settings", R.drawable.ic_action_settings));
		dataList.add(new DrawerItem("Help", R.drawable.ic_action_help));
...
		if (savedInstanceState == null) {

			if (dataList.get(0).isSpinner()
					& dataList.get(1).getTitle() != null) {
				SelectItem(2);
			} else if (dataList.get(0).getTitle() != null) {
				SelectItem(1);
			} else {
				SelectItem(0);
			}
		}

Next update the SelectItem() method. You need to update this according to the “dataList” item position. Fragment should be only need to change when we click in a selectable item not in header or spinner.  So change the case statements to point correct selectable item. (Be careful you may get runtime errors if you update incorrectly.) I delete the  0,1 and 6 case statement and add new case statement for 14,15 and 16 positions .

          public void SelectItem(int possition) {

		Fragment fragment = null;
		Bundle args = new Bundle();
		switch (possition) {

		case 2:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList
					.get(possition).getImgResID());
			break;
		case 3:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 4:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 5:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList
					.get(possition).getImgResID());
			break;
		case 7:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 8:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList
					.get(possition).getImgResID());
			break;
		case 9:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 10:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 11:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList
					.get(possition).getImgResID());
			break;
		case 12:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 14:
			fragment = new FragmentThree();
			args.putString(FragmentThree.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentThree.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 15:
			fragment = new FragmentOne();
			args.putString(FragmentOne.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentOne.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		case 16:
			fragment = new FragmentTwo();
			args.putString(FragmentTwo.ITEM_NAME, dataList.get(possition)
					.getItemName());
			args.putInt(FragmentTwo.IMAGE_RESOURCE_ID, dataList.get(possition)
					.getImgResID());
			break;
		default:
			break;
		}

		fragment.setArguments(args);
		FragmentManager frgManager = getFragmentManager();
		frgManager.beginTransaction().replace(R.id.content_frame, fragment)
				.commit();

		mDrawerList.setItemChecked(possition, true);
		setTitle(dataList.get(possition).getItemName());
		mDrawerLayout.closeDrawer(mDrawerList);

	}

Now update the OnItemClickListener to select the correct fragment when selecting the  drawer item.

...
                private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			if (dataList.get(position).getTitle() == null) {
				SelectItem(position);
			}

		}
	}

Now our customized drawer is completed. You can run this application in a emulator or in a real android device to see it in action. This is only one way which I found to do the customization in a navigation drawer. This may not be the most convenient way to customize the navigation drawer but we can add any other views like check box, buttons and other compatible views to the drawer using this method. Below you can download the source code for basic navigation drawer and custom navigation drawer. See the video demonstration below I’ll explain how to do this tutorial beginning to end.

If you have any issues regarding this tutorial feel free to ask. You can use comment section to communicate with me. If you like this tutorial share this with others. Subscribe our GooglePlus,Youtube and Facebook page to get instant notification about our new tutorials and videos. Or subscribe to your website using your email address to get instant email notification. Thank you very much for visiting my website.

Video Demonstration

 Downloads

Download the Source Code
  • Pelle

    Hi, great tutorial. But i wonder how to add some content in the “Message”. Can you please tell me? Thanks! 🙂

    • Ahamed Ishak

      You can create a separate fragment to Message as the same as the fragment in this tutorial.. Then create a layout file to that fragment.. Then You can design the layout as your requirement. You can access the view from fragment class…. Then update it as you want.. If you don’t know much about fragments in android first you need to learn it.. There are plenty of tutorials in the web.. I’ll do tutorial in fragment in near future. I hope this may help.. If you have further question feel free to ask.. 🙂

  • Carlos Morais

    On the custom nav drawer everytime I click on one of the items on the menu, the user gets reseted back to the first one. How can I disable this or make him keep the one I chose? And how to set the drawer width?

    • Ahamed Ishak

      First of all thank you for informing about the bug in the tutorial… I’ll fix this problem and give you the solution as soon as possible.. For your second question open the “drawer_list_item_template.xml” layout file then you can simply change the “android:layout_width” attribute in list view with this id “android:id=”@+id/left_drawer”. The default size is “240dp”. If you have any further question please feel free to ask..

      • Carlos Morais

        Ok. Thank you. I didnt quite understand the first issue though, if you fix it give me a heads up so I can see.

        • Ahamed Ishak

          Definitely I’ll update you.. Thank you… Share this with others and give support to my website 😀

    • Ahamed Ishak

      Hi I have checked the issue.. Its because drawer is re-initializing in each fragment load. So when you select an item from drawer, it will refresh the item list. As a solution for this you can use shared preferences to keep the selected user in memory when user changed. In “CustomDrawerAdapter” => “getView()” method check shared preference object has already selected user. If object return “null” then select the default user as first item else select the user in the shared preference object…. I hope this may help you to solve this bug.. Thank you.. 🙂

  • Mitali Bhokare

    Hello Sir,
    Your code has really helped me a lot…
    I’ve a small query
    in the switch case of the MainActivity.java when the position is detected accordingly the respective fragments are executed. But i wanna call another Activity class instead of the fragments. I tried by sending intent to call the Activity class and then also wrote startService(class_to_be_called); But its not working. Can you plzz help me to solve the problem. I hope u’ve understood my query.
    Eagerly waiting for the answer. Thank-You

    • Ahamed Ishak

      Hi…. if you try to put startActivity() inside a switch statement it’ll show you runtime error. What you can do is you can start the activity using a “if” condition like below code. first identify the correct position then start the activity inside the “if” condition. In “else” part use the switch statement to select other fragments and change the fragment… Thank you.. I hope this help you.. If you didn’t understand feel free to aks. Check this below code..

      if (possition == 3) {
      Intent i=new Intent(this, TestActivity.class);
      startActivity(i);

      } // end if
      else {

      switch (possition) {

      case 2:

      }//end switch

      fragment.setArguments(args);

      FragmentManager frgManager = getFragmentManager();

      frgManager.beginTransaction().replace(R.id.content_frame, fragment)

      .commit();

      mDrawerList.setItemChecked(possition, true);

      setTitle(dataList.get(possition).getItemName());

      mDrawerLayout.closeDrawer(mDrawerList);

      }//end else

      • Mitali Bhokare

        Thank-You sir for giving the solution…:-) Sir but still it was giving the same problem so i deleted the SelectedItem() method as due to some threading problem it was giving error but now everything is working fine… as i’ve put ‘if-else’ conditions for checking the position in the DrawerItemClickListener() class only. Thank-You Sir for such a great tutorial.

        • Ahamed Ishak

          your welcome.. Have a nice day…

          • Mitali Bhokare

            Hello sir, I just wanted to know how to remove the Right-Click option of Settings which is getting displayed on the ActionBar.

          • Ahamed Ishak

            What is “Right-Click Option of settings” means? I didn’t get your question.. Do you need to remove the menu button from ActionBar.. To remove the menu button
            1. Go to “res=>menu” folder
            2. Open the “main.xml” file
            3. Delete or comment the “item” tag or tags from the file
            4. Save all

            I hope this help you… 🙂

          • Mitali Bhokare

            i wanna actually wanna remove the right corner button click of ActionBar i.e after clicking it display settings option. I’m uploading a picture. I’ve highlighted the part i wanna remove. I hope u get it 🙂

          • Ahamed Ishak

            Okay.. I got it… Do the instruction given in last comment.. You can remove that menu button from there… 🙂

          • Mitali Bhokare

            okieee Thanx a lot sir… Sir plzz keep uploading tutorials related to UI designing of Android they are very helpful…. Thank -you 🙂 🙂

          • Ahamed Ishak

            Your Welcome… Definitely I’ll make more tutorials related to UI… 🙂

  • Sinan

    Hi, great tutorial! Thank you for that! Is it also possible to leave the spinner function out of the user name field and just make it clickable and another activity or fragment can start?

    Greetings from Germany
    Sinan

    • Ahamed Ishak

      Hi Sinan. Thank you for visiting my website. Yes you can customize the spinner view as it your requirements.. In “CustomDrawerAdapter.java” under “if (dItem.isSpinner())” condition there is a “setOnItemSelectedListener”
      for the spinner. There you can create a fragment manager instance and call the
      fragment or activity.

  • D. C.

    Hi, I have a problem when I execute the custom navigation drawer, first I try guided by your tutorial and I have the error, after that, I use the clases uploaded in your .zip file and the result is the same. A null error on method getview on the line: “drawerHolder.headerLayout.setVisibility(LinearLayout.INVISIBLE);”, behind “if (dItem.isSpinner()) {”

    Logcat as follows:

    03-11 17:51:40.425 26170-26170/com.adnavigationdrawer.ad E/AndroidRuntime﹕ FATAL EXCEPTION: main

    Process: com.adnavigationdrawer.ad, PID: 26170

    java.lang.NullPointerException

    at com.adnavigationdrawer.ad.CustomDrawerAdapter.getView(CustomDrawerAdapter.java:79)

    at android.widget.AbsListView.obtainView(AbsListView.java:2325)

    at android.widget.ListView.makeAndAddView(ListView.java:1790)

    at android.widget.ListView.fillDown(ListView.java:691)

    at android.widget.ListView.fillFromTop(ListView.java:752)

    at android.widget.ListView.layoutChildren(ListView.java:1630)

    at android.widget.AbsListView.onLayout(AbsListView.java:2147)

    at android.view.View.layout(View.java:14824)

    at android.view.ViewGroup.layout(ViewGroup.java:4631)

    at android.support.v4.widget.DrawerLayout.onLayout(DrawerLayout.java:714)

    at android.view.View.layout(View.java:14824)

    at android.view.ViewGroup.layout(ViewGroup.java:4631)

    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)

    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)

    at android.view.View.layout(View.java:14824)

    at android.view.ViewGroup.layout(ViewGroup.java:4631)

    at com.android.internal.widget.ActionBarOverlayLayout.onLayout(ActionBarOverlayLayout.java:374)

    at android.view.View.layout(View.java:14824)

    at android.view.ViewGroup.layout(ViewGroup.java:4631)

    at android.widget.FrameLayout.layoutChildren(FrameLayout.java:453)

    at android.widget.FrameLayout.onLayout(FrameLayout.java:388)

    at android.view.View.layout(View.java:14824)

    at android.view.ViewGroup.layout(ViewGroup.java:4631)

    at android.view.ViewRootImpl.performLayout(ViewRootImpl.java:1987)

    at android.view.ViewRootImpl.performTraversals(ViewRootImpl.java:1744)

    at android.view.ViewRootImpl.doTraversal(ViewRootImpl.java:1000)

    at android.view.ViewRootImpl$TraversalRunnable.run(ViewRootImpl.java:5670)

    at android.view.Choreographer$CallbackRecord.run(Choreographer.java:761)

    at android.view.Choreographer.doCallbacks(Choreographer.java:574)

    at android.view.Choreographer.doFrame(Choreographer.java:544)

    at android.view.Choreographer$FrameDisplayEventReceiver.run(Choreographer.java:747)

    at android.os.Handler.handleCallback(Handler.java:733)

    at android.os.Handler.dispatchMessage(Handler.java:95)

    at android.os.Looper.loop(Looper.java:136)

    at android.app.ActivityThread.main(ActivityThread.java:5057)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:515)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:605)

    at dalvik.system.NativeStart.main(Native Method)

    Any ideas? Thanks!!

    • Ahamed Ishak

      hm… my suggestion is to compare your code with my code. Some small mistake in your code may be a reason for this error. Please check layout files. Check your class related to spinner view. Check below code in getview method which will initialize the all layout objects..

      drawerHolder.headerLayout = (LinearLayout) view
      .findViewById(R.id.headerLayout);
      drawerHolder.itemLayout = (LinearLayout) view
      .findViewById(R.id.itemLayout);
      drawerHolder.spinnerLayout = (LinearLayout) view
      .findViewById(R.id.spinnerLayout);

      There can be mistake in onCreate() metohd in MainActivity.java which will lead to this error. Try to use my MainActivity.java class with your adapter class. Still if you didn’t get a solution please let me know I’ll help you.

      Thank you…

      • D. C.

        Error was in my layout files. Great tutorial, greetings!! 😉

        • Ahamed Ishak

          Thank you 🙂 have a nice day..

  • John

    Can you demonstrate how to add a tab to a nav drawer?

    • Ahamed Ishak

      Okay I’ll try to make separate tutorial in tabs in android.. Subscribe to our channel So you will not miss. 😀

      • John

        Great thanks, So basically a Navigation Drawer (Message, Likes, Games, etc) with tabs of 3+ inside each one of the categories.

  • ranzo312

    Hi, awesome tutorial!!!! But how can i erase your name on the top left on menu and add another name and icon ?

    • Ahamed Ishak

      You need to change below lines in CustomDrawerAdapter.java class.

      userList.add(new SpinnerItem(R.drawable.user1, “Ahamed Ishak”,

      “ishakgmail.com”));

      userList.add(new SpinnerItem(R.drawable.user2, “Brain Jekob”,

      “brain.jgmail.com”));

      • ranzo312

        Thanks man !!!

  • rohit

    How can i implement a splash screen before the navigation drawer screen?

    • Ahamed Ishak

      It is very easy. you need to create a separate activity to splash screen.. Google it you will find many tutorials. Check below tutorial.. it will help you..

      http://www.androidhive.info/2013/07/how-to-implement-android-splash-screen-2/

      • Guest

        i implemented the splash screen as shown there. But the app is crashing even before starting. the error being shown is that it cannot resolve the MainActivity class.
        probably this intent is not getting exceuted -> Intent i = new Intent(SplashScreen.this, MainActivity.class);
        startActivity(i);

      • Guest

        Actually i just want to display the name of the app before the main navigation drawer starts up. can you tell me how it can be done?

      • rohit

        Yipeee.. its working now 🙂 thanks 😀

        • Ahamed Ishak

          😀 😀 you’re welcome.. 😀

          • rohit

            is it possible to show a layout with multiple thumbnails like it is there on the menu of our mobiles? it is showing out of memory error 🙁

          • Ahamed Ishak

            Can you post a image of the menu in your mobile. I can’t understand which menu you referring

          • rohit

            like this layout:
            (when i am viewing the layout in xml file, it is showing perfectly.
            But when i am running the app, it is showing out of memory error and crashing )
            http://cdn3.pcadvisor.co.uk/cmsdata/features/3347925/Android_App_Menu.png

          • Ahamed Ishak

            Hey Do you want to create a app drawer like this in navigation drawer? Or you want to create a separate activity for this?

          • rohit

            in the navigation drawer.

          • Ahamed Ishak

            hm… Try a Gridview in the layout file. I never tried this kind of layout file. So I can’t tell you why it is showing out of memory error. I’m recommending you to post this question in stackoverflow.

          • rohit

            Now, i have a independently running gridview and an independently running navigation drawer.. but when i am implementing the gridview layout in the navigation drawer, it is crashing! how do i make both of it work together?? can you provide me the sample code?

          • Ahamed Ishak

            I can provide a sample code but it take time… These days I have tight schedules. I don’t have time to try your requirement at the moment.. If you can wait I can give a try.

          • rohit

            sure 🙂 till then even i will try to work it out 🙂

  • Marc

    Thank you for this tutorial I managed to run the basic navigation drawer..

    I have a favor if you can add a tutorial for the Navigation Drawer with Expandable List view… Im having problem integrating other codes to yours..

    I want to my project to have a two parents and in this parents have atleast for example 3 childs for the expandable list view and the other list view will just be a list view with no child to expand… thanks

    Output like this
    http://i.stack.imgur.com/SNBAA.png

    • Ahamed Ishak

      This tutorial should work with Expandable List view.. First try to implement this in a separate project without try to implement this directly to your code… implementing a Expandablelistview inside a listview sometime may not possible. I try to implement this in with a Expandable listview and give you the correct feedback. 🙂

      • Marc

        thank you… if you have time please make a tutorial for the expandable view for navigation drawer like the spinner view on your site because many new developers like me is looking for that…

        🙂

        UPDATE:
        at first try I got a force close when trying to implement the expandable list view on your basic navigation drawer..

        2nd try it does not force close but in the navigational drawer there is no item listed…

        3rd try force close again

        Maybe i will wait for your tutorial but still I will try my best to figure this out. thanks in advance…

      • Marc

        Maybe I will wait for your tutorial or the correct way to do this… Im new to android development and Im looking forward for your feedback…

        So far I tried making a simple expandable list view with only text on a new project and im successful but when I tried putting it on the basic nav drawer that you provided above… I failed…

        Thank you so much for now ill subscribe on all your social pages so that im updated and maybe soon when your done the tutorial ill try it out…

        • Ahamed Ishak

          Sorry to say I don’t have time to try this…. But definitely I’ll give a try on this.. Please be patient.. As soon as I find the solution I’ll update you.. 🙂

  • Pingback: Android Custom Navigation Drawer | Saiful Haqqi()

  • ranzo312

    can you make a tutorial about how to implement a sync adapter ?

    • Ahamed Ishak

      hm.. That is a good one to make a tutorial. I’ll do a tutorial on Sync Adapters 🙂
      Subscribe to my website or subscribe your social pages you will not miss it.
      Thank you..

      • ranzo312

        thanks again !!!

  • Adys

    Hi Ahamed. I am new in this area so I don’t understand too much now. Your tutorials are great. But I have a question. For this tutorial, it is possible that each items in drawer to have a different image background? Thanks

    • Ahamed Ishak

      Yes it is possible. In your custom adapter inside the getview() method first get a LinearLayout object from your custom layout file. Then after getview() method give a background to the layout by setBackground() method in layout object.

      • Adys

        So. Inside getView(int position, View convertView, ViewGroup parent){

        }

        I must add this?

        And after this i have to edit layout/fragment_layout_one,fragment_layout_two and fragment_layout_three?

        Thanks

        • Ahamed Ishak

          Nope… Don’t do that.. you will find lots of errors by doing it. Do it like below.. All below codes are implemented in custom adapter view in basic navigation drawer


          @Override
          public View getView(int position, View convertView, ViewGroup parent) {
          // TODO Auto-generated method stub

          DrawerItemHolder drawerHolder;
          View view = convertView;

          if (view == null) {
          LayoutInflater inflater = ((Activity) context).getLayoutInflater();
          drawerHolder = new DrawerItemHolder();


          drawerHolder.lytBackground=(LinearLayout) view.findViewById(R.id.linlyout_bakgrd) // Access the xml LinearLayout and convert to android object

          view.setTag(drawerHolder);

          } else {
          drawerHolder = (DrawerItemHolder) view.getTag();

          }

          drawerHolder.lytBackground.setBackground(view.getResources().getDrawable(R.drawable.ic_launcher));

          return view;
          }

          private static class DrawerItemHolder {
          TextView ItemName;
          ImageView icon;
          LinearLayout lytBackground;
          }

          • Ahamed Ishak

            I update the code..

          • Adys

            hello again. i did everything like you said but i have 1 error and I can’t get rid of it
            This is the error:
            linlyout_bakgrd cannot be resolved or is not a field

          • Ahamed Ishak

            You need to create a LinearLayout with id “linlyout_bakgrd” in custom_drawer_item.xml file. Otherwise it try to access a non existing linearlayout. It was my mistake I didn’t mention about that in the replay. It seems you’re a beginner in android development.

            To solve the issue change the linlyout_bakgrd to “itemLayout”. Already there is Linearlayout in “custom_drawer_item.xml”. So you can use that layout without creating a new layout..

            drawerHolder.lytBackground=(LinearLayout) view.findViewById(R.id.itemLayout)

            Hope this solve your problem 🙂

          • Adys

            thank you. now everything works fine

  • Nicola Regattieri

    Hi I`m really starting, and I could complete tutorial, but I was not able to change navigation drawer to white colour like example, it just appears on black color.
    someone could help?

    • Nicola Regattieri

      solved: Just moved project to IntelliJ and works..
      Very good information I really thank you for sharing this!! (Y)

  • Jack Ozer

    Very good tutorial!

    One question:

    The title (header layout) is still clickable.

    It doesn’t do anything because of the change in OnItemClick, but still changes color when clicking it (which is obviously confusing to the user).

    what am I doing wrong?

    • Ahamed Ishak

      Hi @jackozer:disqus Sorry for late reply.. Sorry to tell at the moment I don’t have solution for your problem. I didn’t try to solve the problem in depth because I’m little busy these days. I’ll try to give a solution in future.. If you find a solution please state it here.. Thank you for the information..

      • Selva Amalraj

        Hi Ahamed Ishak, thank u for d great tutorial it really helps me a lot,but am struck up with the above question of Jack Ozer- Title click, do u have any solution on that, can u pls share me…

  • Matwosk

    Thanks a lot for great tutorial. I have also one question. Is it possible use navigation drawer in DEFAULT activity? (I mean in Manifest no LAUNCHER activity)

  • Hi Ahamed! Great Tutorial!!! 🙂
    One Question: How can I retrieve the value of the spinner from a Fragment?

    Thanks!!!! 🙂

    • Ahamed Ishak

      you can use Shared Preference to store the value then retrieve from fragment.

  • Sorry guy for disturbance…I have a last question to ask you: I would refresh a fragment on item selected on spinner…can I do this? Any tips?

    Thanks!

    • Ahamed Ishak

      You can do it.. but you need to use some way access the mainActivity through the adapter. I can’t tell a specific solution. Try it by yourself if you found a solution post a comment.. Sorry for late reply

  • Kittu

    Ahamed Ishak this was a great tutorial. I am implementing the custom navigation drawer, I want to remove the name and email id from the top and the icons from the left of the navigation bar. How do I achieve this?

    • Ahamed Ishak

      You need to create your own custom adapter to do this… Or you can edit my adapter class and custom_drawer_item.xml layout file.. Try to understand the code.. Then you will find the mechanism to do it.

      • Kittu

        I did it dude! Thanks for your suggestion! I have also removed the spinner, but in the layout I could see a gap in the place where the spinner used to be.

        • Ahamed Ishak

          Did you delete the Linear Layout with id spinnerLayout in custom_drawer_item.xml. Delete it if you didn’t.

          • Kittu

            Yes I did that, but the space on top is still empty

          • Ahamed Ishak

            Hm.. Can you post your main Activity code here.. Sometime you may adding a new item to that position.. Or mail your application to tutecentral@gmail.com. I’ll check the code.

          • Kittu

            I am getting “Delivery to the following recipient failed permanently” when I am trying to mail you. Please provide a different address if possible.

          • Ahamed Ishak

            I cannot be… I’m getting mails from others.. Its working perfeclty.. I send you an email to your mail.. Check it..

          • Kittu

            I have sent you the project, please check it

          • Ahamed Ishak

            I’ll check the application and replay you before tomorrow..

          • Kittu

            ok dude!

          • Kittu

            Thanks I have done it!

  • Bingi Nataraj

    Hi,.,. i done the same ThanQ for dis great Tutorial ,.,., and i have a Query ,.,
    How can fix the Menu Icon at Right of the top and onClick i should slide Right to Left ,.,
    How can i fix,. plz give some suggestion ,.,. thanQ,.,.

    • Ahamed Ishak

      change the listview gravity to right on activity_main.xml

      android:layout_gravity=”right”

      like this

      • Bingi Nataraj

        ThanQ so much bro i did it,.,. and also need to add some Java code ,.,. i’m sharing it here, in feature some one might be be need it,.,

        IN MAINACTIVITY.JAVA replace it,

        mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,R.drawable.ic_drawer, R.string.app_name, R.string.app_name) {

        @Override
        public boolean onOptionsItemSelected(MenuItem item) {
        if (item != null && item.getItemId() == R.id.action_settings)
        {
        if (mDrawerLayout.isDrawerOpen(Gravity.RIGHT)) {
        mDrawerLayout.closeDrawer(Gravity.RIGHT);
        } else {
        mDrawerLayout.openDrawer(Gravity.RIGHT);
        }
        }
        return false;
        }
        public void onDrawerClosed(View view) {
        getActionBar().setTitle(mTitle);
        invalidateOptionsMenu(); //Setting, Refresh and Rate App
        }
        public void onDrawerOpened(View drawerView) {
        getActionBar().setTitle(mDrawerTitle);
        invalidateOptionsMenu();
        }
        };

        ThanQ so much for helping,.,.. 🙂

        • Ahamed Ishak

          Please post the question in stackoverflow to get good answer for this. Because I never tried to implement this in right. So I can’t tell you the correct codes to implement it in right side

  • arvdroid vijayvargiya

    type mismatch cannot convert from fragment one to fragment
    plz give me solution .its very important to my project as well

    • Ahamed Ishak

      Please do comparison between your code and sample code. You will find the problem

  • hdpavan

    In the above gmail App screen you pointing a arrow that’s not checkbox
    its radio button 🙂

  • Joy Sequeira

    hey that is a great tutorial!! 😀 but i have one doubt! What if you do not want the item to be displayed at first and only displayed when it is selected…how do you do that??

    • Ahamed Ishak

      Thank you very much.. Sorry I didn’t get your question.. Can you explain it more.. 😀

      • Joy Sequeira

        okay like see in your code right..when i run the code…by default the first item in the in custom drawer list will appear unless you click another item to go to another page. Can you tell me how to modify your code in a such a way that the first item in the list wont appear by default..unless you click i.e. when you run the code!

        • Raul Butuc

          The problem you mention cannot be avoided. When you load your application, you have to call the “SelectItem()” function which selects one of the items.

          In MainActivity.java, you have this code:

          if (savedInstanceState == null) {
          SelectItem(0);
          }

          You see, when this part is reached, you don’t have a “savedInstanceState” (as you run the app the first time), and so, it is “null”. Then, it calls “SelectItem(0)”. This opens the first page. If you want to open the “n-th” page, call “SelectItem(n-1)”, where “n” is the number of the item.

  • Edoardo Serra

    Thank you for your tutorial, it was very clear and precise, but I’d like to implement a Expandable List view all inside of the navigation drawer, unfortunately after several attempts unfortunately I failed the job, Could you please make a tutorial on how to implement it?

    Thanks a lot in advance

    • Ahamed Ishak

      Your welcome.. I’ll try to do a separate tutorial on that 😀

      • Edoardo Serra

        Really? I would be very grateful! thank you very much! 😀

  • Guest

    Hi! How i have learn and understand FramgmentManager.replace() method will keep previous fragments, or no? If yes not better set id and reuse fragment?

  • Andreas Penner

    Great Tutorial, and it works like a charm!
    But what if I want to start my App with the second Item selected in the Spinner?

    • Ahamed Ishak

      you need to use shared preferences to make the second one selected

    • Raul Butuc

      In order to remember the user which is logged in you can either use a “SharedPreferences” approach like Ahamed suggested, or if you are willing to, and consider it useful, use a MySQLite database which will store this data (and maybe more – such as user’s subscriptions/likes/etc. – depending on the purpose of your application)

  • Ung Tú

    getactionbar().setdisplayhomeasupenabled(true) nullpointerexception

    i run app and:…

    java.lang.RuntimeException: Unable to start activity ComponentInfo{vn.irain/vn.irain.activities.MainActivity}: java.lang.NullPointerException

    at android.app.ActivityThread.performLaunchActivity(ActivityThread.java:2180)

    at android.app.ActivityThread.handleLaunchActivity(ActivityThread.java:2230)

    at android.app.ActivityThread.access$600(ActivityThread.java:141)

    at android.app.ActivityThread$H.handleMessage(ActivityThread.java:1234)

    at android.os.Handler.dispatchMessage(Handler.java:99)

    at android.os.Looper.loop(Looper.java:137)

    at android.app.ActivityThread.main(ActivityThread.java:5041)

    at java.lang.reflect.Method.invokeNative(Native Method)

    at java.lang.reflect.Method.invoke(Method.java:511)

    at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:793)

    at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:560)

    at dalvik.system.NativeStart.main(Native Method)

    Caused by: java.lang.NullPointerException

    at vn.irain.activities.MainActivity.onCreate(MainActivity.java:133) //

    at android.app.Activity.performCreate(Activity.java:5104)

    at android.app.Instrumentation.callActivityOnCreate(Instrumentation.java:1080)

    line 133:
    // //getActionBar().setDisplayHomeAsUpEnabled(true);
    //getActionBar().setHomeButtonEnabled(true);

    Please help me!

    • Ahamed Ishak

      There is a null object in your MainActivity.java. Try to find and change the null object

  • Pablo Carrascal

    Hi!

    I’ve downloaded your code and it’s perfect. Great tutorial! But it has a bug…

    Whenever I click one item in the ListView, it shows a toast with the text “User Changed”, and I didn’t click the spinner. How can we fix this?

    Thanks for your help

    • Remi

      Hi Pablo!

      Try this method, it works for me 🙂
      In your CustomDrawerAdapter.java cut code from:

      DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);
      if (dItem.isSpinner()) {
      //…
      //all code from here also
      //…
      }

      and paste it here:

      if (view == null) {
      //…
      view.setTag(drawerHolder);

      //paste code here

      }else {
      drawerHolder = (DrawerItemHolder) view.getTag();
      }

      After that you probably need to do simple trick like this, to avoid firing OnItemSelected method when spinner is first created.

      http://stackoverflow.com/questions/5624825/spinner-onitemselected-executes-when-it-is-not-suppose-to/5918177#5918177

      Hope it helps!

      • Pablo Carrascal

        Thank you!! It worked like a charm 😀 Now I can finish my project.
        Good luck with your tutorials and see you soon.

      • Selva Amalraj

        @disqus_giYjxubG4t:disqus, Hi thanks for d solution..its working but … now am having new problem…. while scrolling the navigation drawer list, i could see the items repeating .. .pls help me out…..

  • Jamie Cartwright

    hi, Ive imported your code into eclipse and ran it, ive noticed it always reverts back to 1st user when screen rotates, how do i stop it doing that, thanks in advance

    • Ahamed Ishak

      you need to use sharedpreferences to keep the 1st user always on.

    • Raul Butuc

      In order to remember the user which is logged in you can either use a “SharedPreferences” approach like Ahamed suggested, or if you are willing to, and consider it useful, use a MySQLite database which will store this data (and maybe more – such as user’s subscriptions/likes/etc. – depending on the purpose of your application)

  • Saeed Hassanpour

    Hi!

    Thank you for your tutorial, but how can I run on android 2.2

    • Raul Butuc

      Hi! You can’t run this on Android 2.2. That is because the Navigation Drawer implementation by Google requires a minimum Android API level of 11.
      Sorry.

  • Irene Chhangte

    I’m new to android. This is a great tutorial. Can you please do coding for action bar search and display list view image in the fragments on this same codes?
    🙂

  • Terrel

    How can I add a single ImageView and TextView with its own xml layout on top of ListView instead of SpinnerItem like it is in Google+ app?

    • Raul Butuc

      Customize it.
      Instead of Spinner.xml, SpinnerItem.java and CustomSpinnerAdapter.java you will create three custom files (like MyCustomView.xml, MyCustomItem.java and MyCustomItemAdapter.java). The only difference between your files and the ones in this tutorial will be that you have 1x ImageView and 1x TextView.

      It really is that simple 🙂

  • MF6265

    Hey Ahamed, great Tutorial, thank you!
    Is there a way to center the DrawerItems in the Drawer horizontal?

    • Raul Butuc

      Hey, I think that what you are looking for is this:

      android:gravity=”center_horizontal”

      Hope it helps 🙂

      • MF6265

        thanks for the help! 🙂

        • Raul Butuc

          No problem, glad I could help 🙂

  • alexlopezit

    Hey GREAT tutorial, do you think you can do another tutorial about how to integrate Salesforce login (https://developer.salesforce.com/mobile/getting-started/android#native) to this sample app or perhaps tell me how to do that?
    Thanks

  • Alfeu Santos

    Very good step-by-step tutorial!

  • Prateek

    Thanx a lot 🙂

  • Alain Pimentel

    This is a great tutorial, thanks!

  • Nandan Pandya

    sir, I don’t want any user information I just want simple navigation drawer with only images

    I’ve done changes but when I remove following line which I guess is for that user information it shows runtime error
    this is from Activity_Main.java
    // dataList.add(new DrawerItem(“”));
    kindly help me on this
    thanks in advance

    • Raul Butuc

      When you remove that line, you don’t insert any data into your “dataList”, which means your list will be empty. That will result in an app crash.

      To use only images in your navigation drawer, you can use a simple layout consisting of one ImageView.

      However, if you are not sure how to implement that one, I rather suggest you pick up a beginner tutorial on general android programming first.

  • Emrys Pau

    Thank you for this.

  • Skrutten

    Thnx for a great tut.
    Just one question:
    How can one change the backgroundcolor of the selected item in the navigationdrawer?

    • Raul Butuc

      Hey. In order to do that, you have to go to your “res” folder. If you don’t have a folder called “drawable”, then create it. After that, inside it, create two files let’s say “my_custom_background.xml” and “my_custom_background_pressed.xml”, then, inside them type this (in this example I work with gradients):

      my_custom_background.xml

      my_custom_background_pressed.xml

      Instead of @color/… you can simply put the hex code for the color, as: #FF9400 (ie: android:startColor=” #FF9400″)

      Now create another file in the “res/drawable” folder, called “selector.xml”, and inside it put this code:

      selector.xml

      For it to work, you have one more step to do: set the background of your DrawerItem layout to “@drawable/selector”. Like this:

      Your custom layout for the DrawerItem

      Hope it helps you 🙂

  • Patrick Simpelo

    Help!

    I had the same issue as Ung Tú below, so I comment the two consecutive “getActionBar()…” calls because there were bigger issues causing this.

    For some reason, all the Fragment.java files cannot be found..

    In the log, an error for each switch condition is as follows:

    “Could not find class ‘com.example.navigationdrawer.Fragment’, referenced from method com.example.navigationdrawer.MainActivity.SelecItem”

    And finally the lines that force close the program:

    “FATAL EXCEPTION: main

    java.lang.NoClassDefFoundError: com.example.navigationdrawer.FragmentOne
    at com.example.navigation.MainActivity.SelectItem(MainActivity.java:116)
    at com.example.navigation.MainActivity.onCreate(MainActivity.java:96)

    ………
    ……..”

    Please help. I do not know how to solve this and I’ve have tried several methods. Even importing the Fragment files (which should not even be needed).
    import com.example.navigationdrawer.FragmentOne
    …..

    • Ahamed Ishak

      Have you try my sample code. If not I recommending you to do a comparison between your code and sample code.

      • Patrick Simpelo

        I have tried it. I also did a side by side comparison of your code AND even tried importing the project.

        • Ahamed Ishak

          Do you get this problem in my sample code too?

          • Patrick Simpelo

            Yes I did. I just tried it right now again

  • MSR

    sorry i’m new here. i tried to follow your tutorial, but after i copy the java coding there is so many error –

    “Class requires API level 11 (current min is 8): android.app.Fragment”

    how can i fix this error

    somebody please help me…

    • Ahamed Ishak

      To use navigation Drawer your application need use min API level as 11. Open your AndroidManifest.xml file then change the min sdk version to 11.

      • Guest

        wooo…so helpful… thank

      • MSR

        wow…. so helpful… thank

      • Guest

        Another problem in SelectItem(int position) in MainActivity.java class.
        i send you the print screen

        • Adam Probert

          You need to import the fragment classes

    • Jake Wollan

      Change min API in Android Manifest

  • MSR

    Another problem in SelectItem(int position) in MainActivity.java class

    i attch you the printscreen

  • Abed Shoujaa

    a very great tut. I have a question how to change the position of the action bar button from left to right thanks

  • Legend

    Can i put a navigation drawer in a canvas with custom view

    • Jake Wollan

      Yes. Just do, well, exactly what you just said.

  • temp

    Thanks for the manual! How made header not clickable?

    • Jake Wollan

      XML – Clickable

      • temp

        I already tried. not working

        • Jake Wollan

          make an instance of the object in your fragment class and do it from there.

  • Jake Wollan

    Hey thanks for this. I have manipulated this a lot, and it has taught me a whole lot. The only thing I do not understand is how which listItem the spinner is applied to. Is this defined in the XML? How would I go about changing the spinner option to another list item? Thanks.

    • Ahamed Ishak

      Thank you.. Check the MainActivity.java file. In onCreate method you can see items are adding to the listview using add( ) method (dataList.add(…..)). There I have enable the spinner view by
      dataList.add(new DrawerItem(true)); // // adding a spinner to the list
      to change the position of the spinner view simply change the place you’re enabling the spinner.

      • Jake Wollan

        Okay I tried that before, and it was giving me a null pointer. I’ll try again. I’m sorry, but would you by chance have a working method to open a PDF file in an app without using webview?

      • Jake Wollan

        Thanks, I tried it before, but something was causing null pointer, would that be the corresponding number of cases? Works now. One more question – what exactly is the purpose of the get view passed 4 & 5 is that just for the spinners ? thanks.

  • Brett

    Hey man awesome tutorial. Everything is working great. One question though how to I add ui components to each view now. Say I wanted a button in messages or a list view within likes. Any help is appreciated.

    • Ahamed Ishak

      You can add UI components to the layout xml file which is associated with message fragment

      • Brett

        Thanks Ahamed, What if I want to open an activity from the nav drawer. i have tried passing an intent from the case that is selected but i get a force close but it still strangely opens the activity that i wanted upon selecting ok on the error. Any idea of what i could be doing wrong. here is my code

        case 7:
        Intent i = new Intent(MainActivity.this, CreateWord.class);
        startActivity(i);
        break;

        • Jake Wollan

          Make sure you have declared your Activity in your Android Manifest.

        • nishant

          Im also getting the same problem…Did u find the solution??

  • Khaled Yabroudi

    thanx for great tutorial , I have one question, how can I add button at bottom of this navigation drawer ?

  • Jake Wollan

    Hello. Is there a way to populate the drawer in a new activity?

  • Troy Zuroske

    I used your tutorial and it works great for what you said it would do. The problem I am having is I am using Google Maps with it and now my map will not respond to my touch or any buttons on the screen for that matter. Only the slider responds to the swipe. How can fix this? If I can not, is there anyway I can just make the top icon the button that brings out the panel (as it already does) without the slide? Essentially I am attempting to copy what Google Maps actually does with their actual application, bring the slider out over the map and place back and the map still is interactive. Thank you in advance.

  • Ashkan Hesaraki

    Thanks for awesome tut. What if I need my app min sdk version to be 9?

  • Bryan WH

    Tutorials on this site are awesome. Always just what i was looking for. Thanks for another great one!

  • Gelli Ravi Kumar

    How to develop this kind of feature in Android 2.x

    • Favas Ishaque Nalakath

      You would need to import android support library v4 to your project

  • khadija

    hi thanks for this tutorial how can i change what see if i click Message or help plz help me

  • I am a blogger, and I understand how hard it is to come up with such a great tutorial. Thanks for your effort.

  • Alireza saemi

    thank u so much . do it work on gradle build system !? i persuit 3 tutorial and non of them works in android studio and gradle build system .
    oh source code is available . thank u for source code .

  • Alireza saemi

    woooooooooow import it as gradle project and thank u finally after 3 tutorial faild to run on new studio and gradle yours works well ..

    thank u s much u made a deep smile on my tired face . hope u get every thing u want in this life

    • Alireza saemi

      it works i imported it . need to say for import project to android studio and use gradle .. there is little hint that made me busy for hours .

      u are lif saver . u made smile on my face after 3 days of trying make custom Nav leg !

      • Ahamed Ishak

        Its nice to hear good feedback. Thank you..

  • Omar Adel

    but how can i add anything to my data list ??
    or how can i add text in .. “likes” ??
    @ahamedishak:disqus plz reply

    • Ahamed Ishak

      Do you need to add new item in to the navigation drawer? or do you need to add items to likes fragment.? what do you need?

      • Omar Adel

        when i click on any item , i find nothing .. now how can i add something to show it in my items ??? ..
        or in this photo ..
        when i click in home item i find “Home” and Home pic how can i change it ??

      • Omar Adel

        Here is it

  • erick Vasquez

    Hi, I have a little problem, I created that, but my items description and image, move randomly!

    • Ahamed Ishak

      There should be a problem with our code. Please try to debug your code.

  • Emmalyn Abache

    hi sir, is there any way to add a fragment in this navigation drawer? like map fragment? hope you will noticed me. Thanks in advance.

    • Ahamed Ishak

      Yes you can use map fragment with navigation drawer. No problem with that. It should work fine.

  • waseem ahmad

    Hi Sir I Want to creat A customadaptor Instead Of Spinner ….it Will Show Logged User Image And His Info >..Then How To creat That Adaptor ….U have Mentioned In Ur Example Google Plus Pic Above …then How to Creat Ahmad Sir …..

  • Ismael Martinez

    hi! how can i listen an onclikEvent from a button on fragmentHome.xml in fragmentHome.java and not in main activity???

    fspecifically.

    if i put a button in fragment_layout_one.xml with onclik event as hello.

    and i put:

    public void hello(View v){…} in mainActivity.java, works

    but if i put the same in FragmentOne.java not works!!!! 🙁

    i want that it works with the second way.

    regards.

  • Alex Mansour

    Hey,

    Thank you for this great work you done .
    The project is works very well for me, but i’m trying to remove the spinner from the customized drawer, so i need the customized one because it has the titles but i need it without spinner, i already make it invisible but the area keep reserved i tried many ways to delete it , but the app crashes on run time . So what is the best way to resolve this issue ?

    Thanks .

    • Ahamed Ishak

      It means you didn’t understand the tutorial. Try to understand the tutorial. Then It easy to do the modification. You need to change almost all the files to change it.

  • Emmalyn Abache

    Hi sir,can I ask if how can i call a listview on this kind of navigation drawer?

    • Ahamed Ishak

      Can you explain more about your problem. Navigation Drawer use a listview to show the content

  • Sam

    Hello, this is a great tutorial! I made it up to where you add the spinner but i wont be needing that functionality so i stopped after the drawer was setup, however, now whenever i switch from Messages to any other fragment i crash, any ideas?

  • Alec

    First of all : Hi everyone!

    Second: i’m facing an issue when i try to launch the app, it says:

    java.lang.SecurityException: Permission Denial ; this requires android.permission.INTERACT_ACROSS_USERS_FUL

    Any idea @ahamedishak:disqus

    • Ahamed Ishak

      Try to add below permission on AndroidManifest.xml

      • Alec

        Same issue… 🙁
        I’m gonna try again to build the app but this time i won’t use copy-paste. Hope it will work.
        Thanks anyway! i’ll be back with a post if it works.

  • Guido Merlini

    Hi ishak, don’t know if it’s my fault or not, but whenever i switch user the method “getview” in customdraweradapter switches it back to the default. is it a known issue to you?

  • Alec

    Hello again @Ahamed Ishak !
    I have 1 more question and I really need your help for this one:
    I want to customize the Navigation Drawer and add to it some headers like you did in this tutorial. The thing is that in your example the headers are mixed with the spinner and I don’t know how to remove the spinner and leave only the headers.
    So i’m asking you, how do I add only the headers?

    I would really appreciate your help.

  • Kpoch

    @ahamedishak:disqus Hello, im totally new on Android Develop, i have some experience on C++ and ASM.

    Ive downloaded the code posted here and read it a bit, but what to edit to put content in each Menu, for example in message i want t display some information with a few pics and the same with the others.

    Thankyou

  • Aaddy

    Hello, im nt able to launch the app…it says ” Unfortunately, NavigationDrawer has stopped.
    what is the problem ?

    • Michael

      Look at your logcat in Android Studio when you get that problem and try to find the lines in your code where you’re having Exceptions. They will most likely occur in MainActivity.java. good luck!

  • Ayumi Azami

    Hello! I’ve got a problem about this.. and it suggests me to create an “OnItemSelectedListener” and remove the “@Override ” annotations.. It’s on getView() method.. What should I do then? Thank you in advance! 🙂

    drawerHolder.spinner.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3) {

    Toast.makeText(context, “User Changed”,
    Toast.LENGTH_SHORT).show();
    }

    @Override
    public void onNothingSelected(AdapterView arg0) {
    // TODO Auto-generated method stub

    }
    });

  • aymen

    thanks for this great tutoriel

  • Sachin Tanpure

    Hi Ahamed..Thanks for such great tutorial..

    I found some issue while implementing code. Whenever my screen orientation change getView method call in CustomDrawerAdapter class but convertView parameter is always null. because of this i cant persist screen on orientation change.All set back to default states.

    Please help me..
    here is my code
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
    // TODO Auto-generated method stub
    DrawerItemHolder drawerHolder;

    View view = convertView;

    if (view == null)
    {
    LayoutInflater inflater = ((Activity) context).getLayoutInflater();
    drawerHolder = new DrawerItemHolder();

    view = inflater.inflate(layoutResID, parent, false);
    drawerHolder.ItemName = (TextView) view.findViewById(R.id.drawer_itemName);
    drawerHolder.icon = (ImageView) view.findViewById(R.id.drawer_icon);
    drawerHolder.spinner = (Spinner) view.findViewById(R.id.drawerSpinner);
    drawerHolder.title = (TextView) view.findViewById(R.id.drawerTitle);
    drawerHolder.headerLayout = (LinearLayout) view.findViewById(R.id.headerLayout);
    drawerHolder.itemLayout = (LinearLayout) view.findViewById(R.id.itemLayout);
    drawerHolder.spinnerLayout = (LinearLayout) view.findViewById(R.id.spinnerLayout);

    view.setTag(drawerHolder);
    view.setSaveEnabled(true);
    }
    else
    {
    drawerHolder = (DrawerItemHolder) view.getTag();
    }

    DrawerItem dItem = (DrawerItem) this.drawerItemList.get(position);

    if (dItem.isSpinner())
    {
    drawerHolder.headerLayout.setVisibility(LinearLayout.INVISIBLE);
    drawerHolder.itemLayout.setVisibility(LinearLayout.INVISIBLE);
    drawerHolder.spinnerLayout.setVisibility(LinearLayout.VISIBLE);

    // List userList = new ArrayList();
    // get users from table and add it in to spinnerlist
    // getUsersDetails();
    // for(int i=0;i<arrUsersrDetails.size();i++)
    // {
    // HashMaphash=new HashMap();
    // hash=arrUsersrDetails.get(i);
    // userList.add(new SpinnerItem(R.drawable.user,hash.get(“display_name”),hash.get(“user_email”)));
    // }
    //userList.add(new SpinnerItem(R.drawable.user1, “Ahamed Ishak”,”ishak@gmail.com”));
    //userList.add(new SpinnerItem(R.drawable.user2, “Brain Jekob”,”brain.j@gmail.com”));

    if(drawerHolder.spinner.getAdapter()==null)
    {
    adapterSpinner = new CustomSpinnerAdapter(context,R.layout.custom_spinner_item, userList);
    drawerHolder.spinner.setAdapter(adapterSpinner);
    }
    drawerHolder.spinner.setOnItemSelectedListener(new OnItemSelectedListener()
    {
    @Override
    public void onItemSelected(AdapterView arg0, View arg1, int arg2, long arg3)
    {
    // TODO Auto-generated method stub
    //drawerHolder.spinner.setSelection(arg2);
    //adapterSpinner.getItem(arg2).getName();
    //Toast.makeText(context, “User Changed”, Toast.LENGTH_SHORT).show();
    if(callback != null)
    {
    callback.SelectSpinnerUser(adapterSpinner.getItem(arg2).getName());
    }
    //String userName= spinner
    // if(context instanceof MainActivity_MNS)
    // {
    // ((MainActivity_MNS)context).SelectSpinnerUser(“sachin”);
    // }
    }
    @Override
    public void onNothingSelected(AdapterView arg0)
    {
    // TODO Auto-generated method stub
    }
    });
    }
    else if (dItem.getTitle() != null)
    {
    drawerHolder.headerLayout.setVisibility(LinearLayout.VISIBLE);
    drawerHolder.itemLayout.setVisibility(LinearLayout.INVISIBLE);
    drawerHolder.spinnerLayout.setVisibility(LinearLayout.INVISIBLE);
    drawerHolder.title.setText(dItem.getTitle());
    }
    else
    {
    drawerHolder.headerLayout.setVisibility(LinearLayout.INVISIBLE);
    drawerHolder.spinnerLayout.setVisibility(LinearLayout.INVISIBLE);
    drawerHolder.itemLayout.setVisibility(LinearLayout.VISIBLE);
    drawerHolder.icon.setImageDrawable(view.getResources().getDrawable(dItem.getImgResID()));
    drawerHolder.ItemName.setText(dItem.getItemName());
    }
    return view;
    }

  • Fanliver

    I use Android studio 1.0.1
    I create a new project and copy you text code to my project.
    I can not build it if i add the android-support-v4.jar as Library

    If i don’t add that jar file, I can build project, but when I run it with Genymotion Emulator on Android 5.0, I got an Exception:
    “Unable to start activity ComponentInfo{navigationdrawer.tutecentral.com.navigationdrawer/navigationdrawer.tutecentral.com.navigationdrawer.MainActivity}: java.lang.NullPointerException: Attempt to invoke virtual method ‘void android.app.ActionBar.setDisplayHomeAsUpEnabled(boolean)’ on a null object reference”
    at the line: getActionBar().setDisplayHomeAsUpEnabled(true);

    I have tried many tutorial about Android navigation drawer, included the one at http://developer.android.com/. But i got the same exception.
    Could you tell me how to fix it. 🙁

    • thisIsYourAnswer

      you need to use getSupportActionBar(), not getActionBar(), to get at the appcompat-v7-supplied action bar backport

    • atif

      change getActionBar() to getSupportAction Bar() and ur prblm vl be solved

  • Benny Kal

    is there anyway to make the drawers when selecting items, instead of creating fragments, it creates activities?
    I posted this comment first without checking the previous comments, but i will breeze through after posting hoping there is.

  • Naushad Anwar Siddiqi

    dear i want to use Webview (website) with fragment2, could you tell me where should i post the syntax … i can’t find it out properly as beginner, is it will be in activity_main or in FragmentTwo.java , & after r.layout.______ what should be in there?

    protected void onCreate1(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    setContentView(R.layout.

    s

  • Paweł Ogrodnik

    Hey, I did as you mention in tutorial but still got some errors – looks like i am missing some variables, but dont know where should I initiate them. I am using android studio 1.1.0. Any ideas? Thanks!

    Error:(99, 41) error: cannot find symbol variable main

    Note: C:UsersPawełDownloadsNavigationDrawerNavigationDrawerNavigationDrawerappsrcmainjavacomexamplepawenavigationdrawerMainActivity.java uses or overrides a deprecated API.

    Note: Recompile with -Xlint:deprecation for details.

    Error:Execution failed for task ‘:app:compileDebugJava’.

  • mojtaba

    Hi Ahmaed .
    I use Android studio 1.1.0 .
    I followed your tutorial until end of Step 4 . When i run app , i see NullPointerException .
    So i debug app and i understand that onPostCreate() method executes before onCreate() and
    when app run at first time the mDrawerToggle is null .

    if i comment mDrawerToggle.syncState(); then app runs but NavigationDrawer doesn`t work .

    How can i fix it ?

    Thanks

  • exc

    Hi Ahmaed

    How to modify the contents of each item in the item on navigation drawer,.,??
    please help me,.,!!

  • Ric Dela Cruz Ferrancullo III

    Thanks for the great tutorial.

  • anshul reejonia

    Thanks a lot !!!!

  • Artur Ziomek

    Thanks man! You helped me with two thing: Custom Navigation Drawer And Custom List View using in fragment. I had problem with this. Then I decided to reset info about creating Custom Drawer. In clear project I created own drawer based on this tutorial, then i wanted to create custom list view in fragment, based on creating listview for drawer, and it’s working ;p When I searching info in web about this I always get big tuts which one not works for me ;p With your description is preaty easy.

  • Ankit Kumar

    Your Tutorial was ok…

  • Michael

    Great tutorial!

    In the part were you make public void SelectItem(int possition){} method in the MainActivity.java file i get an error on the line fragment = new FragmentOne() in the switch statement for case 0, case 1, case 2, case 3 until the last case. The error says;

    “incompatible types”
    “required: android.support.v4.app.Fragment, ”
    “found: com….”

    I followed your steps;

    Goto Following Path “Your Android SDK Drive” sdkextrasandroidsupportv4
    Copy “android-support-v4.jar” file
    Paste it in “lib” folder in your application

    I couldn’t find a folder named lib so I pasted in the folder named libs.

    How do I fix this problem?

  • Michael

    I’m now getting a new error in MainActivity.java sating;
    “Incompatible types
    Required: android.support.v4.app.FragmentManager
    Found: android.app.FragmentManager”

    I’m stuck

  • Michael

    Hi again,

    When I compile for the first time i get this error

    Error:Execution failed for task ‘:app:dexDebug’.
    > com.android.ide.common.process.ProcessException: org.gradle.process.internal.ExecException: Process ‘command ‘C:Program FilesJavajdk1.7.0_45binjava.exe” finished with non-zero exit value 2

    I have searched online for a solution but nothing has helped.

    • Michael

      I fixed this by fixing some other issue and rebuilding.

      • Brandon Solis

        what did you see?!?

  • Akash Biswas
  • Michael

    My FragmentOne class is no different from the one posted in the
    tutorial above and yet android studio throws a FATAL EXCEPTION that says
    resource not found 0x0 on ivIcon.setImageDrawable(…)

    If you’ve run into this problem before and have a solution please share it because I’ve been stuck with this problem for 3 days and haven’t found a clear solution.

    Here’s my code;

    public class FragmentOne extends Fragment {

    ImageView ivIcon;
    TextView tvItemName;

    public static final String IMAGE_RESOURCE_ID = “ic_action_cloud”;//iconResourceID
    public static final String ITEM_NAME = “itemName”;

    public FragmentOne() {}

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

    View view = inflater.inflate(R.layout.fragment_layout_one, container, false);

    ivIcon = (ImageView) view.findViewById(R.id.frag1_icon);
    tvItemName = (TextView) view.findViewById(R.id.frag1_text);
    tvItemName.setText(getArguments().getString(ITEM_NAME));
    ivIcon.setImageDrawable(view.getResources().getDrawable(getArguments().getInt(IMAGE_RESOURCE_ID),view.getContext().getTheme()));

    Thanks!

    • Michael

      Figured out what the problem was.

      I was importing unwanted external resources and that was causing
      conflicts with accessing right resources so I removed those import
      statements and replaced the problematic line with,

      ivIcon.setImageDrawable(view.getResources().getDrawable(getArguments().getInt(IMAGE_RESOURCE_ID)));

      Which worked.

      Thanks for the help.

  • Sanghita Chakraborty

    Great tutorial…easy explanation…working example

  • Asha

    great tutorial…. thanks a lot…

    Could you please help me in the following scenario. I am newbie in android and just started learning.

    I have fragments like

    navDrawer – > A –> A1 — > A1.1

    navDrawer – > B –> B1 — > B1.1

    and vice versa

    How to navigate to inner fragments and come back to the main fragments. Also change the main navDrawer icon to back arrow in inner fragments too. Thanks

  • Szabczy

    Hi,
    Great tutorial!

    My only question is: how can You make the program to remember the last spinner-item selected after restart.
    Currently upon startup the

    drawerHolder.spinner
    .setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
    public void onItemSelected(AdapterView arg0,
    View arg1, int arg2, long arg3)
    routine gets called automatically with 0 value for arg2, arg3 – thus resetting the selection previously made.

    Thank You for your help.

  • Appu

    Hi, Great Tutorial!

    I want to remove drop down list in Custom Drawer..How to do?

  • Phong Lục

    wow, great tut. tks you !
    form vietnameee

  • zereshk

    thanks for code and perfect tutorial
    I need my drawer to open from right side of the screen so i put the listview in right gravity:

    but when I click on drawer item to open, the program got force close and this is my logcat error:

    java.lang.IllegalArgumentException: No drawer view found with gravity LEFT

    how can i solve it?

  • Kishan Solanki

    NIice Tutorial. Really Helpful !

  • sajjad

    hi thanks for tutorial.
    but how we can show navigation in other activities?

  • Umesh Raginda Munasinghe

    grate job, thanks very much …

  • Half Moon

    Best Navigation UI Design: Click Here

  • sarosh

    Dear Friend Ahamad Ishaq
    I found your tutorial very helpful and amazing you code very well but while implementing i got the null pointer exception as you mentioned and forced ” Be careful you may get runtime errors if you update incorrectly.) I delete the 0,1 and 6 case statement and add new case statement for 14,15 and 16 positions ”

    if position is 0 then it is the case which is not in the switch and we try to force to do this..

    fragment.setArguments(args);
    FragmentManager frgManager = getFragmentManager();
    frgManager.beginTransaction().replace(R.id.content_frame, fragment).commit();

    here ‘args’ & ‘fragment’ both are null… how can I get rid of this situation.

    I tried doing this..

    case 0:
    args.putString(“ITEM_NAME”,dataList.get(possition).getItemName());
    args.putInt(“IMAGE_RESOURCE_ID”,dataList.get(possition).getImgResID());
    break;

    But not Worked… plz help me
    Regards Sarosh Madara

    Jazakallah..

  • Tim Pierce

    Dear Ahamad

    I tried to follow your tutorial, but when it came time to download the source code and JsonServices (0.3.4) dll’s the download page didn’t work

  • Mal

    The resourcepack link is not working?

  • jerofad

    The Resource pack link not working please can you help out?

  • Rick

    Hey @ahamedishak:disqus the downloading links are not working.. You mind checking ’em out and update the links again? Appreciate your help in advance. And besides, awesome tutorial. Cheers!

  • Rick

    Hi All,
    Are you having this downloaded ResourcePack and SourceCode ??
    For some reasons, the downloading links are not working. If you have these, then please mail me to gladiatorrick@gmail.com at the earliest.
    Thanks in advance 🙂

  • Michel Carvajal

    Great job!! Only one thing, the link to download Resource Pack is broken, you need a new one. I get icons from other app.

  • Hiago Paraguaçú

    Links for download it’s broken :///

  • aryan roy

    code is complete but i face some of errors and its in fragment so i am use activity and for activity i was got code from androidtechtutorials.blogspot.in

  • Selva Kumar

    Link for download is broken,Could anybody please help me solve this?

  • faisal porag

    Can i get the source code ?????

  • suvv mohanty

    getActionBar().setDisplayHomeAsUpEnabled(true) I am getting null pointer exception,could someone help me please.I am running the code in android studio.

  • Great article 🙂 thanks for sharing it.

    i have also found good android tutorial link for navigation drawer and other materials.
    Android Navigation Drawer Tutorials
    latest android tutorials

  • Shlok Ishan

    Where to downnload the missing icons…

    // Add Drawer Item to dataList
    dataList.add(new DrawerItem(“Message”, R.drawable.ic_action_email));
    dataList.add(new DrawerItem(“Likes”, R.drawable.ic_action_good));
    dataList.add(new DrawerItem(“Games”, R.drawable.ic_action_gamepad));
    dataList.add(new DrawerItem(“Lables”, R.drawable.ic_action_labels));
    dataList.add(new DrawerItem(“Search”, R.drawable.ic_action_search));
    dataList.add(new DrawerItem(“Cloud”, R.drawable.ic_action_cloud));
    dataList.add(new DrawerItem(“Camara”, R.drawable.ic_action_camera));
    dataList.add(new DrawerItem(“Video”, R.drawable.ic_action_video));
    dataList.add(new DrawerItem(“Groups”, R.drawable.ic_action_group));
    dataList.add(new DrawerItem(“Import & Export”,
    R.drawable.ic_action_import_export));
    dataList.add(new DrawerItem(“About”, R.drawable.ic_action_about));
    dataList.add(new DrawerItem(“Settings”, R.drawable.ic_action_settings));
    dataList.add(new DrawerItem(“Help”, R.drawable.ic_action_help));

    adapter = new CustomDrawerAdapter(this, R.layout.custom_drawer_item,