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="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/pager"
       android:layout_width="match_parent"
       android:layout_height="match_parent" />

</RelativeLayout>

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 {
    @Override
    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="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="net.joerichard.viewpagertutorial.FirstFragment"
   android:background="#FF0000">

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

</FrameLayout>

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) {
        super(fm);
    }

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

    @Override
    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(R.id.pager);
        MyViewPagerAdapter adapter = new MyViewPagerAdapter(getSupportFragmentManager());
        pager.setAdapter(adapter);

SourceCode
APK file

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