Android Navigation → Android ViewPager – Camposha

Android Navigation

Android Navigation

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
    
    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);
        } 
    } 

 

Leave a Reply

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

Price

Free

Rating

Not enough ratings to display
X