Tabs using ViewPager – Android Tutorial

person Vinothkumar Arputharajfolder_openAndroidaccess_time March 15, 2015

Hope you already mastered using ActionBar with the help of our previous tutorials. Please refer to the tutorials Android ActionBar Tutorial and Android ActionBar using Appcompat_V7 library for better understanding (if you still have any doubts).
See flowing Steps :

  1. Create main layout file res/layout/activity_main.xml with ViewPager widget.
  2. The ViewPager is a layout widget in which each child view is a separate page (a separate tab) in the layout.
  3. Create separate layout files in res/layout folder for the fragments.
  4. Create custom FragmentPagerAdapter. This holds the fragments and adds support to navigate between the tabs.
  5. Add an implementation of the ActionBar.TabListener interface.
  6. You can pass data from activity to the Fragment using getArguments() method.

1. Manifest file

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example.actionbartabs"
    android:versionCode="1"
    android:versionName="1.0">
    <uses-sdk android:minSdkVersion="14" />
    <application android:label="@string/app_name"
        android:icon="@drawable/ic_launcher"
        android:theme="@style/AppTheme">
        <activity android:name="MainActivity" android:label="@string/app_name">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

2. Activity layout file
Main activity layout file

<android.support.v4.view.ViewPager xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/view_pager"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

First tab fragment layout

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
    <LinearLayout android:orientation="vertical"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="center">
        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="@string/fragment_main"
            android:autoLink="web"
            />
    </LinearLayout>
</FrameLayout>

Layout for second tab fragment

<TextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:textSize="24sp"
    android:padding="32dp" />

Third fragment layout whit one ImageView and TextView

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical" >
    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/image"
        android:layout_gravity="center"
        />
    <TextView
    android:id="@android:id/text1"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center"
    android:textSize="24sp"
    android:padding="32dp" />
</LinearLayout>

3. Main Activity code
Note that this activity extends ActionBarActivity from the support library to enable backward compatibility. So the same application will work in older android version devices also without any problem.

Note we should mention setNavigationMode(ActionBar.NAVIGATION_MODE_TABS) to get support to add Tabs to the ActionBar.

package com.example.actionbartabs;
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
public class MainActivity extends ActionBarActivity {
	private MyFragmentPageAdapter mPageAdapter;
	private ViewPager mViewPager;
	private ActionBar ab;
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		// setup actionbar
		// get the actionbar
		ab = getSupportActionBar();
		// Specify that the Home/Up button should not be enabled, since there is no hierarchical
		// parent.
		ab.setHomeButtonEnabled(false);
		// Specify that we will be displaying tabs in the action bar.
		ab.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
		// This adapter will hold the fragments
		mPageAdapter = new MyFragmentPageAdapter(getSupportFragmentManager());
		// Get the view pager widget from the activity layout
		mViewPager = (ViewPager) findViewById(R.id.view_pager);
		// Set the page adapter to the view pager
		mViewPager.setAdapter(mPageAdapter);
		// This listener will be triggered when the user swipes between the pages
		mViewPager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
			@Override
			public void onPageSelected(int position) {
				// Set the selected navigation item corresponding to the current position
				ab.setSelectedNavigationItem(position);
			}
		});
		// Iterate the page adapter and add the fragments to the view pager
		for (int i = 0; i < mPageAdapter.getCount(); i++) {
			// Create a new tab
			Tab newTab = ab.newTab();
			// Set tab title
			newTab.setText(mPageAdapter.getPageTitle(i));
			// Set tab listener
			newTab.setTabListener(new MyTabListener(mViewPager));
			// Add the tab to the actionbar
			ab.addTab(newTab);
		}
	}
}

Create a page adapter extending FragmentPagerAdapter to set the fragments to the tabs.

package com.example.actionbartabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
/**
 * FragmentPagetAdapter returns the current selected fragment
 * @author vinothkumar.a
 *
 */
public class MyFragmentPageAdapter extends FragmentPagerAdapter {
	// Total tabs count
	private static final int PAGE_COUNT = 3;
	public MyFragmentPageAdapter(FragmentManager fm) {
		super(fm);
	}
	@Override
	public Fragment getItem(int i) {
		switch (i) {
		case 0:
			// Display the main fragment
			return new MainFragment();
		case 1:
			// Display second fragment
			Fragment fragment = new SecondFragment();
			// Pass extra values using bundle extras as arguments.
			Bundle args = new Bundle();
			args.putString("EXTRAS", "This data is passed as bundle argument");
			fragment.setArguments(args);
			return fragment;
		case 2:
			// Display second fragment
			Fragment fragment3 = new ThirdFragment();
			return fragment3;
		default:
			return new MainFragment();
		}
	}
	@Override
	public int getCount() {
		return PAGE_COUNT;
	}
	@Override
	public CharSequence getPageTitle(int position) {
		// returns the page title for the current tab
		return "Tab Title " + (position + 1);
	}
}

Create a tab listener which implements ActionBar.TabListener

package com.example.actionbartabs;
import android.support.v4.view.ViewPager;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
public class MyTabListener implements ActionBar.TabListener{
	private ViewPager mViewPager;
	public MyTabListener(ViewPager viewPager) {
		this.mViewPager = viewPager;
	}
	@Override
	public void onTabReselected(Tab tab,
			android.support.v4.app.FragmentTransaction arg1) {
	}
	@Override
	public void onTabSelected(Tab tab,
			android.support.v4.app.FragmentTransaction arg1) {
		// set the current item on tab selected
		mViewPager.setCurrentItem(tab.getPosition());
	}
	@Override
	public void onTabUnselected(Tab tab,
			android.support.v4.app.FragmentTransaction arg1) {
	}
}

The ViewPager container is all set to display the tab content. Now add some UI elements in the fragments.

package com.example.actionbartabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class MainFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_main, container, false);
        return view;
    }
}

The main activity is sending some String extras to the SecondFragment.java. We can get those extra values using getArguments() method and set it to the TextView.

package com.example.actionbartabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class SecondFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	 View view = inflater.inflate(R.layout.fragment_two, container, false);
         Bundle args = getArguments();
         ((TextView) view.findViewById(android.R.id.text1)).setText(args.getString("EXTRAS"));
         return view;
    }
}

Third fragment layout simply displays one ImageView and one TextView

package com.example.actionbartabs;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class ThirdFragment extends Fragment {
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
            Bundle savedInstanceState) {
    	 View view = inflater.inflate(R.layout.fragment_three, container, false);
         ((TextView) view.findViewById(android.R.id.text1)).setText("Third Fragment");
         return view;
    }
}

4. Demonstration
First tab with static content

First tab
First tab

Second tab with content passed from the Activity

Second tab
Second tab

Leave a Reply

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

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code class="" title="" data-url=""> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong> <pre class="" title="" data-url=""> <span class="" title="" data-url="">