Tuesday, 18 December 2012

The simplest way to use a ViewPager

The swiping gesture has become so popular that your app could be considered out-dated if it does not have this feature. In fact, adding it is so easy that there is no reason for you to not add it.

So, let us build a simple application that uses the ViewPager. I will be using the FragmentStatePagerAdapter for this. You can also use the FragmentPagerAdaper. The only difference between the two is, the former saves more memory but creates your fragment every time. By default, at any given time, it will keep at most three fragments alive - the one that is currently visible to the user, and the ones to its immediate left and right.

This application we are creating now displays different websites on different pages. That is, you swipe to change the website that is currently visible.

Let us create the layout of our activity first. It holds only the ViewPager.
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_height="match_parent" >


Next, let us create the layout of our fragment. It holds only a WebView. Obviously, his is the component that will be rendering the websites.
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" >

        android:layout_height="match_parent" />


Okay, now we are all done with the layouts. Let us write some Java code. First, let us create our Fragment code. I will be using the Fragment class from the support library, but you can use SherlockFragment in case you are using the ActionBarSherlock library.
package com.sample.jdepths;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.WebView;
import android.webkit.WebViewClient;

public class BrowserFragment extends Fragment {

    WebView browser; 
    String url;
    public View onCreateView(LayoutInflater inflater, 
         ViewGroup container, Bundle savedInstanceState) {

        View view=inflater.inflate(
        browser.setWebViewClient(new WebViewClient());
        // Just load whatever URL this fragment is
        // created with.
        return view;
    // This is the method the pager adapter will use
    // to create a new fragment
    public static Fragment newInstance(String url){
        BrowserFragment f=new BrowserFragment();
        return f;

All we are doing in this code is, initialize the browser, and load the URL that was passed to the fragment when it was created.

Next, we will write the code that makes the Activity. I will be creating a FragmentActivity, but you can also use the SherlockFragmentActivity if you are using the ActionBarSherlock library.
package com.sample.jdepths;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentActivity;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.ViewPager;

public class MainActivity extends FragmentActivity {

    ViewPager pager;
    FragmentStatePagerAdapter adapter; 
    /* Just some random URLs
    * Each page of our pager will display one URL from this array
    * Swiping, to the right will take you to the next page having
    * the next URL.
     String[] toVisit={
    public void onCreate(Bundle savedInstanceState) {
        adapter=new FragmentStatePagerAdapter(
            public int getCount() {
                // This makes sure getItem doesn't use a position
               // that is out of bounds of our array of URLs
               return toVisit.length;
            public Fragment getItem(int position) {
                // Here is where all the magic of the adapter happens
                // As you can see, this is really simple.
                return BrowserFragment.newInstance(toVisit[position]);
        //Let the pager know which adapter it is supposed to use

There, that is all you need to do to use the ViewPager. Just add the INTERNET permission to the manifest, and you are ready to run it.

Here is a screenshot of the pager in action,
While swiping left

Hope that was helpful. Let me know what you think by commenting. I would love to read your comments.

1 comment:

  1. Nice Tutorial....
    One Question im using the same above code and display a bunch of html pages as book reader....
    How can i index each page