Android Club – ViewPager tutorial

In this tutorial, I will show how to use ViewPager. First of all, let’s create Android Application project. Open activity_main.xml. Put ViewPager there:

<RelativeLayout xmlns:android=""
   xmlns:tools="" android:layout_width="match_parent"
   android:layout_height="match_parent" tools:context=".MainActivity">

       android:layout_height="match_parent" />


Now, you can create fragment Right button of your mouse on your package->New->Fragment->Blank. This will create new Fragment. So clear Fragment code, so after that you should have only onCreateView method inside your fragment.

public class FirstFragment extends Fragment {
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_first, container, false);

Now go to fragment_first layout and change background color and text view text.

<FrameLayout xmlns:android=""
   xmlns:tools="" android:layout_width="match_parent"

    <!-- TODO: Update blank fragment layout -->
    <TextView android:layout_width="match_parent" android:layout_height="match_parent"
       android:text="First fragment"/>


Create fragments like this as much as you want. I created 3 of them. Next step is to create adapter for ViewPager

public class MyViewPagerAdapter extends FragmentStatePagerAdapter {

    public MyViewPagerAdapter(FragmentManager fm) {

    public Fragment getItem(int position) {
        switch (position)
            case 0:
                return new FirstFragment();
            case 1:
                return new SecondFragment();
            case 2:
                return new ThirdFragment();
        return null;

    public int getCount() {
        return 3;

I called my adapter – MyViewPagerAdapter. getCount method returns how many fragments I will have. getItem method returns respective fragment for page by its position. Now reference our ViewPager and set our ViewPagerAdapter(inside MainActivity’s onCreate method):

        ViewPager pager = (ViewPager) findViewById(;
        MyViewPagerAdapter adapter = new MyViewPagerAdapter(getSupportFragmentManager());

APK file

That’s it now we create ViewPager which holds fragments.