Android ViewPager – A Quick Guide

by Mir Suhail

Android ViewPager is the layout manager that allows user to flip left and right (screen slide) through pages of data. ViewPager is a layout widget in which each child view is a separate page (a separate tab) in the layout.

swiping

Screen slides are transitions between one entire screen to another and are common with UIs like setup wizards or slideshows. Here, we will see  how to do screen slides with a ViewPager provided by android support library. ViewPagers can animate screen slides automatically.

ViewPager – How Does it Work

ViewPager class is a layout manager or a container that allows user to swipe left and right through a set of pages that you supply. The term “pages” suggests something like an web page but this is only a very loose analogy.

offscreen_pages

The idea is that ViewPager works with a PageAdapter to supply Views that represent each page. The basic idea is that ViewPager keeps track of what page should be visible on screen and then asks the PagerAdapter to get View hierarchy that needs to be displayed.  For example, ViewPager might request page 4 and PagerAdapter generates or otherwise retrieves View object for page.

In practice, low level mechanism of working with a simple PagerAdapter is a bit more tricky than working with a Fragment based PagerAdapter . In this scheme of things each page to be displayed is organised as a Fragment and View hierarchy that ViewPager needs is obtained via Fragment’s OnCreateView method. 

The idea is that FragmentPagerAdapter either generates or retrieves Fragment by page number and then internally uses OnCreateView method to generate View hierarchy that ViewPager uses to display the page.

So for all this to work we need:

  1. An Activity with a ViewPager on display as part of its main UI.
  2. A set of Fragments to be used as pages.
  3. A custom  FragmentPagerAdapter that returns the correct Fragment for each page number.ViewPager

Let’s see how to put this into operation but first a small detail that is essential to allow us to actually use a ViewPager.

Creating the Views

Now we will create  a layout file that we will  later use for the content of a fragment. The following example contains a text view to display some text:

<!-- fragment_screen_slide_page.xml -->

<ScrollView

xmlns:android="http://schemas.android.com/apk/res/android"

android:id="@+id/content"

android:layout_width="match_parent"

android:layout_height="match_parent">

<TextView style="?android:textAppearanceMedium"
android:padding="16dp"
android:lineSpacingMultiplier="1.2"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="@string/lorem_ipsum" />

</ScrollView>

 Creating the Fragment

Now we will create a Fragment class that returns the layout that we just created in onCreateView() method. We can then create instances of this fragment in the parent activity whenever we need a new page to display to user:

import
android.support.v4.app.Fragment;...
public class MyFragment extends Fragment {
    public MyFragment(){    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        ViewGroup rootView = (ViewGroup) inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
        return rootView;
    }
}

 Adding a ViewPager

ViewPagers contain built-in swipe gestures to transition through layout  pages containing screen slide animations by default, so we don’t need to create any. ViewPagers use PagerAdapters as a supply for new pages to display, so the PagerAdapter will use the fragment class that we created above.

To begin, we will create a layout that contains a ViewPager:

<!--activity_screen_slide.xml -->
<android.support.v4.view.ViewPager
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/pager"
    android:layout_width="match_parent" 
    android:layout_height="match_parent"
    />
After this, we will create activity that does the following:
  • Sets the content view to be layout with the ViewPager.
  • Creates a class that extends FragmentStatePagerAdapter abstract class and implements getItem() method to supply instances of MyFragement as new pages. The pager adapter also requires that you implement getCount() method, which returns amount of pages the adapter will create (e.g: 4).
  • Hooks up PagerAdapter to theViewPager.
  • Handles the device’s back button by moving backwards in virtual stack of fragments. If the user is already on first page, go back on the activity back stack.
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
...
public class ScreenSlidePagerActivity extends FragmentActivity {
    
    private static final int NUM_PAGES = 4;
    private ViewPager mPager;
    private PagerAdapter mPagerAdapter;

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

        // Instantiate a ViewPager and a PagerAdapter.
        mPager = (ViewPager) findViewById(R.id.pager);
        mPagerAdapter = new ScreenSlidePagerAdapter(getSupportFragmentManager());
        mPager.setAdapter(mPagerAdapter);
    }

    @Override
    public void onBackPressed() {
        if (mPager.getCurrentItem() == 0) {
            super.onBackPressed();
        } else {
            // Otherwise, select the previous step.
            mPager.setCurrentItem(mPager.getCurrentItem() - 1);
        }
    }


    private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
        public ScreenSlidePagerAdapter(FragmentManager fm) {
            super(fm);
        }

        @Override
        public Fragment getItem(int position) {
            return new MyFragment();
        }

        @Override
        public int getCount() {
            return NUM_PAGES;
        }
    }
}

 

To learn more about

Contact Us

Leave a Reply

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

Mobile Research Apps

We have deep expertise in design and development of mobile research apps that work on both iOS and Android securely.

Contact us now

Popular Posts