Android ViewPager


Android ViewPager Tutorial and Examples.

ViewPager is a Layout Manager that allows user to swipe through pages either left or right.

In ViewPager each child view is a separate page (a separate tab) in the layout.

ViewPager is one of the most important navigation features of android as it powers most of those swiping you see in apps. Swiping is these days one of the most popular form of navigation and is quite unique when compared to forms of navigation commonly used in desktop and web apps.

Given that our smartphones have become our personal assistants, the ability to swipe is one of those features that have become so common that we forget how it revolutionized how we use our computers(called smartphones).

In majority of cases, ViewPager gets used alongside Fragments and with tabs.

Thus this provides conveniency in terms of suppling and managing the lifecycle of each page. Fragments remember, are subactivities, and activities represent a single screen. Fragments most oftenly get used as pages.

And it is these pages that we can swipe through via ViewPager.Normally you have to provide an implementation of a PagerAdapter to generate the pages that the view shows.

There are two common PagerAdapter subclasses that we use to generate the pages:

  1. FragmentPagerAdapter - An implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page. Best when navigating between sibling screens representing a fixed, small number of pages.
  2. FragmentStatePagerAdapter- Implementation of PagerAdapter that uses a Fragment to manage each page. This class also handles saving and restoring of fragment's state. Best for paging across a collection of objects for which the number of pages is undetermined. It destroys fragments as the user navigates to other pages, minimizing memory usage.

These are FragmentPagerAdapter and FragmentStatePagerAdapter; each of these classes have simple code showing how to build a full user interface with them.

Normally you can annotate your views with ViewPager.DecorView annotation. Then those views get treated as part of the view pagers 'decor'. You can manipulate a decor view's position via it's android:layout_gravity attribute.

For example:

 <android.support.v4.view.ViewPager
     android:layout_width="match_parent"
     android:layout_height="match_parent">

     <android.support.v4.view.PagerTitleStrip
         android:layout_width="match_parent"
         android:layout_height="wrap_content"
         android:layout_gravity="top" />

 </android.support.v4.view.ViewPager>

Important ViewPager Methods

1. setAdapter()

setAdapter(PagerAdapter adapter)

This method will set a PagerAdapter that will supply views for this pager as needed.

2. setCurrentItem

setCurrentItem(int item)

This method will set the currently selected page.

setCurrentItem(int item, boolean smoothScroll)

This second one will set the currently selected page, but allows you to specify whether to use smooth scroll or not.

Steps in Using ViewPager

Step 1 - Create Project

Create Your android project.

Step 2 - Create Pages

Mostly we use fragments as pages. So we create as many fragments as we want.

public class NewsFragment extends Fragment {...}
public class SportsFragment extends Fragment {...}
public class PoliticsFragment extends Fragment {...}

Each Fragment is normally responsible for its own lifecycle management, we said that earlier.

So you will be overriding some methods inside those Fragments.

Step 3 - Prepare PagerAdapter

Those Fragments are nothing to our ViewPager without a PagerAdapter, whose subclass can can handle those Fragments for our ViewPager to work with.

Given that we are using Fragments we can subclass the FragmentPagerAdapter class, which if your remember we said is an implementation of PagerAdapter that represents each page as a Fragment that is persistently kept in the fragment manager as long as the user can return to the page.

public class MyPagerAdapter extends FragmentPagerAdapter {...}

Some methods will be overriden there.

Step 4 - Add ViewPager in Layout

Mostly in the main layout of your activity:

<android.support.design.widget.CoordinatorLayout>
    ..........

    <android.support.v4.view.ViewPager
        android:id="@+id/mViewpager_ID"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        />

        ...............

</android.support.design.widget.CoordinatorLayout>

Step 5 - Reference ViewPager Object

Reference ViewPager, mostly in your activity, say inside your onCreate() method:


        ViewPager vp= (ViewPager) findViewById(R.id.mViewpager_ID);

Step 6 - Add Fragments/Pages to Your FragmentPagerAdapter

Obvisoul first you instantiate the FragmentPagerAdapter implementation

        MyPagerAdapter pagerAdapter=new MyPagerAdapter(this.getSupportFragmentManager());

In this case the addFragment() is just a custom method we created in our FragmentPagerAdapter implementation:

        pagerAdapter.addFragment(new CrimeFragment());
        pagerAdapter.addFragment(new DramaFrgament());
        pagerAdapter.addFragment(new DocumentaryFragment());

Step 7 - Set Your FragmentPagerAdapter to ViewPager

We use the setAdapter() method. This met

        vp.setAdapter(pagerAdapter);

Step 8 - Use it

Maybe with a Tablayout.

    tabLayout.setupWithViewPager(vp);

Find the full example here.

How to Use a Title Strip Instead of Tabs

Sometimes, instead of rendering the full action bar tab, you may want to provide scrollable tabs with shorter visual profile.

In that case you use PagerTitleStrip with your swipe views.

<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">

    <android.support.v4.view.PagerTitleStrip
        android:id="@+id/pager_title_strip"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="top"
        android:background="#33b5e5"
        android:textColor="#fff"
        android:paddingTop="4dp"
        android:paddingBottom="4dp" />

</android.support.v4.view.ViewPager>

Quick ViewPager Examples and HowTo's

1. How to flip ViewPager to Next or Previous Page
    // ViewPager flips to the next page, no need to worry about crossing the border 
    public static void next(ViewPager viewPager) {
        int position = viewPager.getCurrentItem();
        goPosition(viewPager, position + 1);
    } 

    // ViewPager flips to the previous page, no need to worry about crossing the border 
    public static void last(ViewPager viewPager) {
        int position = viewPager.getCurrentItem();
        goPosition(viewPager, position - 1);
    } 

    // ViewPager flips to the specified page, no need to worry about crossing the border (with page flip animation) 
    public static void goPosition(ViewPager viewPager, int position) {
        goPosition(viewPager, position, true);
    } 

    // ViewPager flips to the specified page, no need to worry about crossing the border 
    // needAnim : Do you need to turn page animation? 
    public static void goPosition(ViewPager viewPager, int position, boolean needAnim) {
        int count = viewPager.getAdapter().getCount();
        if (position >= 0 && position < count) {
            viewPager.setCurrentItem(position, needAnim);
        } 
    } 

Top 5 Android ViewPager Examples

Let's look at some examples.

It's important that we know how to construct applications that can be swiped. Alot of the times while interacting with apps you see the ability to swipe being integrated in modern applications.

This ability in android is enable by a class called android.support.v4.View.ViewPager.

ViewPager gives us this ability to swipe.

Moreover we may want our users to have the ability to click through the tabs and navigate appropriately the application. Users probably intuitively expect this.

So we make use of ActionBar Tabs. Tabs allow us to navigate pages/fragments by clicking them.

Android ViewPager Sliding Tabs Tutorial. Swiping is cool,I have said it before.And there is one android support library class that makes it easy to implement in our apps,the ViewPager.

Android ViewPager Swipe Tabs - Fragments With ListViews.

Hello guys today we discuss how to create Fragments with ListViews and Swipeable Tabs.The listviews shall be simple and have some data.We shall be able to swipe from left and right and vice versa,with help of ViewPager.

Android Viewpager Swipeable tabs tutorial.

This is an android swipe tabs with ListView containing SQLite data.

Android material tablayout Swipe tabs with images tutorial.

Best Regards, Oclemy.

How do You Feel after reading this?

According to scientists, we humans have 8 primary innate emotions: joy, acceptance, fear, surprise, sadness, disgust, anger, and anticipation. Feel free to tell us how you feel about this article using these emotes or via the comment section. This feedback helps us gauge our progress.

Help me Grow.

I set myself some growth ambitions I desire to achieve by this year's end regarding this website and my youtube channel. Am halfway. Help me reach them by:




Recommendations


What do You Think


Previous Post Next Post