Android (support v4) ViewPager tutorial (including source code)

The ViewPager is a GUI component that allows to group views and allows to skip to tab content with swipe. The most popular use of this navigation method is google play menu, where user can choose app categories: GooglePlay tabs Although ViewPager was introduced in later android version Android, here I will show how to implement it in Android 2.3 with supportv4 library.

1. Intro

The component will contain three views, each of them will be a Fragment. Fragments are reusable and allows to keep code cleaner and well organized. To use Fragments and ViewPager, download the support v4 lib and put it in your project’s libs folder. Follow instructions from here:

  • Make sure you have downloaded the Android Support Library using the SDK Manager.
  • Create a libs/ directory in the root of your application project.
  • Copy the JAR file from your Android SDK installation directory (e.g.,<sdk>/extras/android/support/v4/android-support-v4.jar) into your application’s project libs/directory.
  • Right click the JAR file and select Build Path > Add to Build Path.

2. Add ViewPager View to your Activity

<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"
    tools:context=".MainActivity" >

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

</RelativeLayout>

3. Create Fragments that will be displayed in tabs Fragments are objects that extend Fragment (not Activity) and therefore can be placed in an Activity with other fragments. The activity that holds Fragments must extend FragmentActivity class (not the Activity). Fragments also have the lifecycle different from Activity. Here I create three coloured empty fragments. Here is one of them:

import android.support.v4.app.Fragment;

public class FragmentGreen extends Fragment {

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

		View view = inflater.inflate(R.layout.fragment_green, container, false);
		return view;
	}
}

and corresponding layout file:

<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:background="#C7F464">

</RelativeLayout>

4. Create Fragment adapter

Similar to ListView Adapters, here you create class extending the FragmentPagerAdapter and few of its methods. Here you decide which fragments will be displayed in ViewPager. My class looks as follows:

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

public class MyPagerAdapter extends FragmentPagerAdapter {

	private List<Fragment> fragments;

	public MyPagerAdapter(FragmentManager fm) {
		super(fm);
		this.fragments = new ArrayList<Fragment>();
		fragments.add(new FragmentBlue());
		fragments.add(new FragmentGreen());
		fragments.add(new FragmentPink());
	}

	@Override
	public Fragment getItem(int position) {
		return fragments.get(position);
	}

	@Override
	public int getCount() {
		return fragments.size();
	}
}

all of my coloured fragments are kept in an ArrayList. Now its time to use this adapter in my ViewPager view in main activity.

5. Setup ViewPager in Main FragmentActivity

Setting up ViewPager is simple and takes two main steps. Firstly, you need to extend FragmentActivity, and then setup adapter. Full Main Activity code is:

import android.support.v4.app.FragmentActivity;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {

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

		MyPagerAdapter pageAdapter = new MyPagerAdapter(getSupportFragmentManager());
		ViewPager pager = (ViewPager)findViewById(R.id.myViewPager);
		pager.setAdapter(pageAdapter);
	}

}

6. Get the source code

That’s all. Now run your app and swipe your finger to left and right to change colours. Get the source code from here.

7. Detailed fragment lifecycle

See this post to see how to manage fragment’s lifecycle – detect when fragment is shown to the user.

Did I help you?

I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality Donate Button with Credit Cards Thank You!

8 thoughts on “Android (support v4) ViewPager tutorial (including source code)

  1. I still have a problem. When i go to the third fragment and swipe back to the first fragment. The buttons on the first fragment stops working. Any solution to that?

    1. Well, consider the fragment lifecycle. Android loads the current fragment that is visible on the screen and both adjacent ones: the previous and the next one. So on the third fragment you have second and fourth loaded, and the first one gets recreated when you swipe left to the second fragment

      Probably you dont recreate the click listeners.

      See my post with detailed fragment lifecycle

  2. THANK YOU!! I needed just this kinda basic and simple code for base of one school project. Thank you! Now i can start and make the actual program! :D

Give Your feedback: