Android ActionBarSherlock ViewPager Tabs Tutorial

In this tutorial, you will learn how to implement ActionBarSherlock ViewPager Tabs in your Android application. ViewPager allows the user to flip left and right through pages of data. ViewPager is most often used with fragment and tabs, which is a convenient way to supply and manage the lifecycle of each fragments. We will create a viewpager with tabs and on flip left or right will show different fragments. So lets begin…

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 ABSViewPagerTutorial.

Application Name : ABSViewPagerTutorial

Project Name : ABSViewPagerTutorial

Package Name : com.androidbegin.absviewpagertutorial

Open your MainActivity.java and paste the following code.

MainActivity.java

package com.androidbegin.absviewpagertutorial;

import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.ActionBar.Tab;
import com.actionbarsherlock.app.SherlockFragmentActivity;

public class MainActivity extends SherlockFragmentActivity {

	// Declare Variables
	ActionBar mActionBar;
	ViewPager mPager;
	Tab tab;

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

		// Activate Navigation Mode Tabs
		mActionBar = getSupportActionBar();
		mActionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);

		// Locate ViewPager in activity_main.xml
		mPager = (ViewPager) findViewById(R.id.pager);

		// Activate Fragment Manager
		FragmentManager fm = getSupportFragmentManager();

		// Capture ViewPager page swipes
		ViewPager.SimpleOnPageChangeListener ViewPagerListener = new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				super.onPageSelected(position);
				// Find the ViewPager Position
				mActionBar.setSelectedNavigationItem(position);
			}
		};

		mPager.setOnPageChangeListener(ViewPagerListener);
		// Locate the adapter class called ViewPagerAdapter.java
		ViewPagerAdapter viewpageradapter = new ViewPagerAdapter(fm);
		// Set the View Pager Adapter into ViewPager
		mPager.setAdapter(viewpageradapter);

		// Capture tab button clicks
		ActionBar.TabListener tabListener = new ActionBar.TabListener() {

			@Override
			public void onTabSelected(Tab tab, FragmentTransaction ft) {
				// Pass the position on tab click to ViewPager
				mPager.setCurrentItem(tab.getPosition());
			}

			@Override
			public void onTabUnselected(Tab tab, FragmentTransaction ft) {
				// TODO Auto-generated method stub
			}

			@Override
			public void onTabReselected(Tab tab, FragmentTransaction ft) {
				// TODO Auto-generated method stub
			}
		};

		// Create first Tab
		tab = mActionBar.newTab().setText("Tab1").setTabListener(tabListener);
		mActionBar.addTab(tab);

		// Create second Tab
		tab = mActionBar.newTab().setText("Tab2").setTabListener(tabListener);
		mActionBar.addTab(tab);

		// Create third Tab
		tab = mActionBar.newTab().setText("Tab3").setTabListener(tabListener);
		mActionBar.addTab(tab);

	}

}

In this activity, we have created three tabs with tab listeners using the action bar navigation mode tabs. The ViewPager is created by a ViewPagerAdapter class. The tab listener captures the tab position and passes it into the ViewPagerAdapter.

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

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

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

    <android.support.v4.view.ViewPager
        android:id="@+id/pager"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content" >
    </android.support.v4.view.ViewPager>

</RelativeLayout>

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

Open your FragmentTab1.java and paste the following code.

FragmentTab1.java

package com.androidbegin.absviewpagertutorial;

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

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		setUserVisibleHint(true);
	}

}

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

Open your FragmentTab2.java and paste the following code.

FragmentTab2.java

package com.androidbegin.absviewpagertutorial;

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

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		setUserVisibleHint(true);
	}

}

Next, create the third fragment tab. Go to File > New > Class and name it FragmentTab3.java. Select your package named com.androidbegin.absviewpagertutorial and click Finish.

Open your FragmentTab3.java and paste the following code.

FragmentTab3.java

package com.androidbegin.absviewpagertutorial;

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

public class FragmentTab3 extends SherlockFragment {

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

	@Override
	public void onSaveInstanceState(Bundle outState) {
		super.onSaveInstanceState(outState);
		setUserVisibleHint(true);
	}

}

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

Open your ViewPagerAdapter.java and paste the following code.

ViewPagerAdapter.java

package com.androidbegin.absviewpagertutorial;

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 = 3;

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

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

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

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

		// Open FragmentTab3.java
		case 2:
			FragmentTab3 fragmenttab3 = new FragmentTab3();
			return fragmenttab3;
		}
		return null;
	}

	@Override
	public int getCount() {
		// TODO Auto-generated method stub
		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 an XML graphical layout for first 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/Fragment1" />

</RelativeLayout>

Next, create an XML graphical layout for second 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/Fragment2" />

</RelativeLayout>

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

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

fragmenttab3.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/Fragment3" />

</RelativeLayout>

Change the application name and fragment textview texts in strings.xml. Open your strings.xml and paste the following code. Go to res > values > strings.xml

strings.xml

<resources>

    <string name="app_name">ABS ViewPager Tabs Tutorial</string>
    <string name="hello_world">Hello world!</string>
    <string name="menu_settings">Settings</string>
    <string name="title_activity_main">ABS ViewPager Tabs Tutorial</string>
    <string name="Fragment1">This is ActionBarSherlock Fragment 1</string>
    <string name="Fragment2">This is ActionBarSherlock Fragment 2</string>
    <string name="Fragment3">This is ActionBarSherlock Fragment 3</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.absviewpagertutorial"
    android:versionCode="1"
    android:versionName="1.0" >

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

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

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

    </application>

</manifest>

Output :

ActionBarSherlock ViewPagerTabs Screenshot

Source Code 

[purchase_link id=”7902″ text=”Purchase to Download Source Code” style=”button” color=”green”]

Latest comments

hi, i have tried to your tutorial and i really do think this is good but i got into some problem from your tutorial, i tried to add this requestWindowFeature(Window.FEATURE_NO_TITLE); and i the result is i can't start the activity because of this, have any idea to fix this ? i also have tried putting android:theme="@android:style/Theme.Holo.Light.NoActionBar.Fullscreen"> on manifest.xml

irvank

Android ActionBarSherlock ViewPager Tabs Tutorial

how to show json data in two tabs

Sefin Francis

Android ActionBarSherlock ViewPager Tabs Tutorial

hey here the default tab is TAB1 what i want is that when the activity gets launched it should show me default fragment as TAB2 how can i achieve this plz help me

Vinay Mishra

Android ActionBarSherlock ViewPager Tabs Tutorial

Thanks, i love u <3

asdf

Android ActionBarSherlock ViewPager Tabs Tutorial