ActionBarSherlock Side Menu Navigation with Nested ViewPager Fragment Tabs Tutorial

In this tutorial, you will learn how to implement ActionBarSherlock Side Menu Navigation with Nested ViewPager Fragment Tabs in your Android application. The navigation drawer is a panel that transitions in from the left edge of the screen and displays the main navigation options. Using a Side Menu Navigation Drawer allows the user to easily navigate between fragments or activities. The navigation drawer can be brought onto the screen by swiping from the left edge of the screen or by touching the application icon on the action bar. We will create a custom side menu navigation drawer using ActionBarSherlock Library and on selected menu item click will show a fragment and a ViewPager with Tabs. So lets begin…

Download the Latest Support Library

Download the latest support library revision 13 that supports the new Navigation Drawer. 

Link : http://developer.android.com/tools/extras/support-library.html

Replace the old support library (android-support-v4.jar) with the new support library in your ActionBarSherlock Library.

Support Package, revision 13 (May 2013)

Changes for v4 support library:
  • Added DrawerLayout for creating a Navigation Drawer that can be pulled in from the edge of a window.

Prepare your project by importing the ActionBarSherlock Library. Refer to Implementing ActionBarSherlock in Android tutorial.

Create a new project in Eclipse File > New > Android Application Project. Fill in the details and name your project MenuViewPagerTutorial.

Application Name : MenuViewPagerTutorial

Project Name : MenuViewPagerTutorial

Package Name : com.androidbegin.menuviewpagertutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.menuviewpagertutorial;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.MenuItem;

import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.app.Fragment;
import android.content.res.Configuration;
import android.os.Bundle;
import android.support.v4.app.ActionBarDrawerToggle;
import android.support.v4.widget.DrawerLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ListView;
import android.support.v4.view.GravityCompat;

public class MainActivity extends SherlockFragmentActivity {

	// Declare Variables
	DrawerLayout mDrawerLayout;
	ListView mDrawerList;
	ActionBarDrawerToggle mDrawerToggle;
	MenuListAdapter mMenuAdapter;
	String[] title;
	String[] subtitle;
	int[] icon;
	Fragment fragment1 = new Fragment1();
	Fragment fragment2 = new Fragment2();
	private CharSequence mDrawerTitle;
	private CharSequence mTitle;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		// Get the view from drawer_main.xml
		setContentView(R.layout.drawer_main);

		// Get the Title
		mTitle = mDrawerTitle = getTitle();

		// Generate title
		title = new String[] { "Title Fragment 1", "Title Fragment 2" };

		// Generate subtitle
		subtitle = new String[] { "Subtitle Fragment 1", "Subtitle Fragment 2" };

		// Generate icon
		icon = new int[] { R.drawable.action_about, R.drawable.action_settings };

		// Locate DrawerLayout in drawer_main.xml
		mDrawerLayout = (DrawerLayout) findViewById(R.id.drawer_layout);

		// Locate ListView in drawer_main.xml
		mDrawerList = (ListView) findViewById(R.id.listview_drawer);

		// Set a custom shadow that overlays the main content when the drawer
		// opens
		mDrawerLayout.setDrawerShadow(R.drawable.drawer_shadow,
				GravityCompat.START);

		// Pass string arrays to MenuListAdapter
		mMenuAdapter = new MenuListAdapter(MainActivity.this, title, subtitle,
				icon);

		// Set the MenuListAdapter to the ListView
		mDrawerList.setAdapter(mMenuAdapter);

		// Capture listview menu item click
		mDrawerList.setOnItemClickListener(new DrawerItemClickListener());

		// Enable ActionBar app icon to behave as action to toggle nav drawer
		getSupportActionBar().setHomeButtonEnabled(true);
		getSupportActionBar().setDisplayHomeAsUpEnabled(true);

		// ActionBarDrawerToggle ties together the the proper interactions
		// between the sliding drawer and the action bar app icon
		mDrawerToggle = new ActionBarDrawerToggle(this, mDrawerLayout,
				R.drawable.ic_drawer, R.string.drawer_open,
				R.string.drawer_close) {

			public void onDrawerClosed(View view) {
				// TODO Auto-generated method stub
				super.onDrawerClosed(view);
			}

			public void onDrawerOpened(View drawerView) {
				// TODO Auto-generated method stub
				// Set the title on the action when drawer open
				getSupportActionBar().setTitle(mDrawerTitle);
				super.onDrawerOpened(drawerView);
			}
		};

		mDrawerLayout.setDrawerListener(mDrawerToggle);

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

	@Override
	public boolean onOptionsItemSelected(MenuItem item) {

		if (item.getItemId() == android.R.id.home) {

			if (mDrawerLayout.isDrawerOpen(mDrawerList)) {
				mDrawerLayout.closeDrawer(mDrawerList);
			} else {
				mDrawerLayout.openDrawer(mDrawerList);
			}
		}

		return super.onOptionsItemSelected(item);
	}

	// ListView click listener in the navigation drawer
	private class DrawerItemClickListener implements
			ListView.OnItemClickListener {
		@Override
		public void onItemClick(AdapterView<?> parent, View view, int position,
				long id) {
			selectItem(position);
		}
	}

	private void selectItem(int position) {

		FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
		// Locate Position
		switch (position) {
		case 0:
			ft.replace(R.id.content_frame, fragment1);
			break;
		case 1:
			ft.replace(R.id.content_frame, fragment2);
			break;
		}
		ft.commit();
		mDrawerList.setItemChecked(position, true);
		// Get the title followed by the position
		setTitle(title[position]);
		// Close drawer
		mDrawerLayout.closeDrawer(mDrawerList);
	}

	@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 void setTitle(CharSequence title) {
		mTitle = title;
		getSupportActionBar().setTitle(mTitle);
	}

	@Override
	public void onBackPressed() {

		FragmentManager manager = getSupportFragmentManager();
		if (manager.getBackStackEntryCount() > 0) {
			// If there are back-stack entries, leave the FragmentActivity
			// implementation take care of them.
			manager.popBackStack();

		} else {
			// Otherwise, ask user if he wants to leave :) 
			super.onBackPressed();
		}
	}
}

In this activity, we have created some sample titles, subtitles and icons into a string and integer arrays and passed it into MenuListAdapter to display it on a listview as a side menu. On listview side menu click will display the selected fragment together with the title on the action bar. The ActionBarDrawerToggle facilitates the proper interaction behavior between the action bar icon and the navigation drawer.

We have prepared some sample icons for this tutorial. Insert your downloaded sample icons into your res > drawable-hdpi.

Sample Icons

SideMenu Sample Images (7.0 KiB, 3109 downloads)

Next, create an XML graphical layout for your navigation drawer. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file drawer_main.xml and paste the following code.

drawer_main.xml

<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent" >

    <FrameLayout
        android:id="@+id/content_frame"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <ListView
        android:id="@+id/listview_drawer"
        android:layout_width="240dp"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        android:background="#111"
        android:choiceMode="singleChoice"
        android:divider="@android:color/transparent"
        android:dividerHeight="0dp" />

</android.support.v4.widget.DrawerLayout>

Next, create a custom menu adapter class. Go to File > New > Class and name it MenuListAdapter.java. Select your package named com.androidbegin.menuviewpagertutorial and click Finish.

Open your MenuListAdapter.java and paste the following code.

MenuListAdapter.java

package com.androidbegin.menuviewpagertutorial;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

public class MenuListAdapter extends BaseAdapter {

	// Declare Variables
	Context context;
	String[] mTitle;
	String[] mSubTitle;
	int[] mIcon;
	LayoutInflater inflater;

	public MenuListAdapter(Context context, String[] title, String[] subtitle,
			int[] icon) {
		this.context = context;
		this.mTitle = title;
		this.mSubTitle = subtitle;
		this.mIcon = icon;
	}

	@Override
	public int getCount() {
		return mTitle.length;
	}

	@Override
	public Object getItem(int position) {
		return mTitle[position];
	}

	@Override
	public long getItemId(int position) {
		return position;
	}

	public View getView(int position, View convertView, ViewGroup parent) {
		// Declare Variables
		TextView txtTitle;
		TextView txtSubTitle;
		ImageView imgIcon;

		inflater = (LayoutInflater) context
				.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
		View itemView = inflater.inflate(R.layout.drawer_list_item, parent,
				false);

		// Locate the TextViews in drawer_list_item.xml
		txtTitle = (TextView) itemView.findViewById(R.id.title);
		txtSubTitle = (TextView) itemView.findViewById(R.id.subtitle);

		// Locate the ImageView in drawer_list_item.xml
		imgIcon = (ImageView) itemView.findViewById(R.id.icon);

		// Set the results into TextViews
		txtTitle.setText(mTitle[position]);
		txtSubTitle.setText(mSubTitle[position]);

		// Set the results into ImageView
		imgIcon.setImageResource(mIcon[position]);

		return itemView;
	}

}

In this custom menu adapter class, string and integer arrays are set into the TextViews and ImageViews followed by the positions.

Next, create an XML graphical layout for the listview menu item. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file drawer_list_item.xml and paste the following code.

drawer_list_item.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    style="?attr/spinnerDropDownItemStyle"
    android:layout_width="match_parent"
    android:layout_height="?attr/dropdownListPreferredItemHeight"
    android:background="?android:attr/activatedBackgroundIndicator"
    android:orientation="horizontal" >

    <ImageView
        android:id="@+id/icon"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:adjustViewBounds="true" />

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:gravity="center_vertical|left"
        android:orientation="vertical" >

        <TextView
            android:id="@+id/title"
            style="?attr/spinnerDropDownItemStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true" />

        <TextView
            android:id="@+id/subtitle"
            style="?attr/spinnerDropDownItemStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:ellipsize="end"
            android:singleLine="true"
            android:textAppearance="?attr/textAppearanceSmall" />
    </LinearLayout>

</LinearLayout>

Next, create the first fragment. Go to File > New > Class and name it Fragments1.java. Select your package named com.androidbegin.menuviewpagertutorial and click Finish.

Open your Fragments1.java and paste the following code.

Fragments1.java

package com.androidbegin.menuviewpagertutorial;

import com.actionbarsherlock.app.SherlockFragment;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment1 extends SherlockFragment {
	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View rootView = inflater.inflate(R.layout.fragment1, container, false);
		return rootView;
	}

}

Next, create the second fragment. Go to File > New > Class and name it Fragments2.java. Select your package named com.androidbegin.menuviewpagertutorial and click Finish.

Open your Fragments2.java and paste the following code.

Fragments2.java

package com.androidbegin.menuviewpagertutorial;

import java.lang.reflect.Field;
import com.actionbarsherlock.app.SherlockFragment;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Fragment2 extends SherlockFragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		View view = inflater.inflate(R.layout.viewpager_main, container, false);
		// Locate the ViewPager in viewpager_main.xml
		ViewPager mViewPager = (ViewPager) view.findViewById(R.id.viewPager);
		// Set the ViewPagerAdapter into ViewPager
		mViewPager.setAdapter(new ViewPagerAdapter(getChildFragmentManager()));
		return view;
	}

	@Override
	public void onDetach() {
		super.onDetach();
		try {
			Field childFragmentManager = Fragment.class
					.getDeclaredField("mChildFragmentManager");
			childFragmentManager.setAccessible(true);
			childFragmentManager.set(this, null);
		} catch (NoSuchFieldException e) {
			throw new RuntimeException(e);
		} catch (IllegalAccessException e) {
			throw new RuntimeException(e);
		}
	}
}

In this activity,  we have created the ViewPager from a ViewPagerAdapter class.

Next, create an XML graphical layout for the frist fragment. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file fragment1.xml and paste the following code.

fragment1.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/Fragment1" />

</RelativeLayout>

Next, create an XML graphical layout for the viewpager. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file viewpager_main.xml and paste the following code.

viewpager_main.xml

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

    <android.support.v4.view.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <android.support.v4.view.PagerTabStrip
            android:id="@+id/pagerTabStrip"
            android:layout_width="fill_parent"
            android:layout_height="30dp"
            android:layout_gravity="top" >
        </android.support.v4.view.PagerTabStrip>
    </android.support.v4.view.ViewPager>

</RelativeLayout>

Next, create a ViewPager Adapter class. Go to File > New > Class and name it ViewPagerAdapter.java. Select your package named com.androidbegin.menuviewpagertutorial and click Finish.

Open your ViewPagerAdapter.java and paste the following code.

ViewPagerAdapter.java

package com.androidbegin.menuviewpagertutorial;

import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;

public class ViewPagerAdapter extends FragmentPagerAdapter {

	// Declare the number of ViewPager pages
	final int PAGE_COUNT = 2;
	private String titles[] = new String[] { "Tab1", "Tab2" };

	public ViewPagerAdapter(FragmentManager fm) {
		super(fm);
	}

	@Override
	public Fragment getItem(int position) {
		switch (position) {

			// Open FragmentTab1.java
		case 0:
			FragmentTab1 fragmenttab1 = new FragmentTab1();
			return fragmenttab1;

			// Open FragmentTab2.java
		case 1:
			FragmentTab2 fragmenttab2 = new FragmentTab2();
			return fragmenttab2;
		}
		return null;
	}

	public CharSequence getPageTitle(int position) {
		return titles[position];
	}

	@Override
	public int getCount() {
		return PAGE_COUNT;
	}

}

In this ViewPagerAdapter class, we have declared the number of ViewPager pages and on tab switch or flip will show different fragments.

Next, create the first viewpager fragment tab. Go to File > New > Class and name it FragmentTab1.java. Select your package named com.androidbegin.menuviewpagertutorial and click Finish.

Open your FragmentTab1.java and paste the following code.

FragmentTab1.java

package com.androidbegin.menuviewpagertutorial;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;

public class FragmentTab1 extends SherlockFragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Get the view from fragmenttab1.xml
		View view = inflater.inflate(R.layout.fragmenttab1, container, false);
		return view;
	}
}

Next, create the second viewpager fragment tab. Go to File > New > Class and name it FragmentTab2.java. Select your package named com.androidbegin.menuviewpagertutorial and click Finish.

Open your FragmentTab2.java and paste the following code.

FragmentTab2.java

package com.androidbegin.menuviewpagertutorial;

import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import com.actionbarsherlock.app.SherlockFragment;

public class FragmentTab2 extends SherlockFragment {

	@Override
	public View onCreateView(LayoutInflater inflater, ViewGroup container,
			Bundle savedInstanceState) {
		// Get the view from fragmenttab2.xml
		View view = inflater.inflate(R.layout.fragmenttab2, container, false);
		return view;
	}
}

Next, create an XML graphical layout for first viewpager fragment tab. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file fragmenttab1.xml and paste the following code.

fragmenttab1.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/FragmentTab1" />

</RelativeLayout>

Next, create an XML graphical layout for first viewpager fragment tab. Go to res > layout > Right Click on layout > New > Android XML File

Name your new XML file fragmenttab2.xml and paste the following code.

fragmenttab2.xml

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

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="@string/FragmentTab2" />

</RelativeLayout>

Next, change the application name and texts. Open your strings.xml in your res > values folder and paste the following code.

strings.xml

<resources>

    <string name="app_name">Side Menu ViewPager Tabs Tutorial</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="Fragment1">This is Fragment 1</string>
    <string name="FragmentTab1">This is ViewPager Fragment Tab 1</string>
    <string name="FragmentTab2">This is ViewPager Fragment Tab 2</string>
    <string name="drawer_open">Open navigation drawer</string>
    <string name="drawer_close">Close navigation drawer</string>

</resources>

In your AndroidManifest.xml, we need to change the theme style to “Theme.Sherlock” and set your preferable Android minimum SDK version. Open your AndroidManifest.xml and paste the following code.

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.androidbegin.menuviewpagertutorial"
    android:versionCode="1"
    android:versionName="1.0" >

    <uses-sdk
        android:minSdkVersion="4"
        android:targetSdkVersion="15" />

    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/Theme.Sherlock" >
        <activity android:name=".MainActivity" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />

                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>

</manifest>

Output:

MenuViewPagerTutorial ScreenShots

Source Code:  

MenuViewPagerTutorial (4.3 MiB, 1057 downloads)
  • http://www.AndroidBegin.com/ AndroidBegin

    I’ll check on it. Thanks for your feedback.

  • Umar

    coool !!
    haven’t checked if it works but looking forward to implement the layout on my app :)

  • MIKI

    Thaks for that, it realy helps me :D
    But what can I do when I want TextView or AutoCompeteTextView instead the tile (I mean Title Fragment 1 and Title Fragment 2 in ActionBar) nex to button in top-left

  • Balazs Ruda

    Hi,
    I had the same problem on 2.3.
    I deleted the following line from the drawer_list_item.xml;
    android:background=”?android:attr/activatedBackgroundIndicator”
    After this, it works fine.

  • Martin JM

    is this App also compatible with android 2.3?

  • Alexander

    Thank you thank you thank you! Worked perfectly. I wanted to put menu items in xml but had trouble parsing out the icon drawables from xml. The following tutorial helped (hint: int[] becomes TypedArray) http://androidcookbook.com/Recipe.seam;jsessionid=FBBDB8B566AF5762933354F7F6989661?recipeId=1418

    • http://www.AndroidBegin.com/ AndroidBegin

      Hi there, I’m glad this tutorial helped you. :)

  • Alexmuller1416

    how to use intent in the project

  • Tom

    This is makes the app look a lot more professional, thanks for teaching :)

  • JoJo

    Please show me how to add action for fragment 1. Thanks

  • anushya subbiah

    hey thanks for the tutorial.. it was great.. i ran it in my emulator. There was no problem.But when i exported there was a problem. eclipse closed abruptly whenever i finished the export procedure. Any solution for this.

  • Fred

    Thank you very very much for the tutorial. its amazing. this might be a stupid question. but can i add more fragments to the drawer menu. and give seperate tabs for the new fragments. if its possible will you please help me. Thanks anyways.

  • Artem

    Hello!

    Thanks for the tutorial! But here is one question – why we should use child FragmentManager via getChildFragmentManager() instead of accessing FragmentManger directly? Thanks in advance!

  • Albert John Mwanjesa

    Hi,

    First, thank you for your tutorials, they are very helpful.

    With this tutorial I have one problem. It seems that my ActionbarSherlockProject is missing the ActionbarDrawerToggle widget and also the DrawerLayout widget as well. How do I solve this problem?

    Thank you in advance!

  • Andrew

    I try to load strings from resource like this:
    Original: private String titles[] = new String[] { “Tab1″, “Tab2″ };

    Modification:
    Resources titles_array = context.getResources();
    String[] titles = titles_array.getStringArray(R.array.title);

    Unfortunetly app crash always. What else can I do to load titles from resource?

  • Çağrı Çakır

    Great, simple and clear explanation. Thanks.

  • chandu

    very good………….. and thank u for u r Tutorial..

  • Nguyễn Hoàng Anh

    how can I use viewpager tabswipe in actionbar not TabStrip