Android Tutorial: Using the ViewPager

Currently, one of the most popular Widgets in the Android library is the ViewPager.  It’s implemented in several of the most-used Android apps, like the Google Play app and one of my own apps, RBRecorder:

RBRecorder

GooglePlay

The ViewPager is the widget that allows the user to swipe left or right to see an entirely new screen. In a sense, it’s just a nicer way to show the user multiple tabs. It also has the ability to dynamically add and remove pages (or tabs) at anytime. Consider the idea of grouping search results by certain categories, and showing each category in a separate list. With the ViewPager, the user could then swipe left or right to see other categorized lists. Using the ViewPager requires some knowledge of both Fragments and PageAdapters. In this case, Fragments are “pages”. Each screen that the ViewPager allows the user to scroll to is really a Fragment. By using Fragments instead of a View here, we’re given a much wider range of possibilities to show in each page. We’re not limited to just a List of items. This could be any collection of views and widgets we may need. You can think of PageAdapters in the same way that you think of ListAdapters. The Page Adapter’s job is to supply Fragments (instead of views) to the UI for drawing.

I’ve put together a quick tutorial that gets a ViewPager up and running (with the Support Library), in just a few steps. This tutorial follows more of a top-down approach. It moves from the Application down to the Fragments. If you want to dive straight into the source code yourself, you can grab the project here.

At The Application Level

Before getting started, it’s important to make sure the Support Library is updated from your SDK, and that the library itself is included in your project. Although the ViewPager and Fragments are newer constructs in Android, it’s easy to port them back to older versions of Android by using the Support Library. To add the library to your project, you’ll need to create a “libs” folder in your project and drop the JAR file in. For more information on this step, check out this page on the Support Library help page on the developer site.

Setting Up The Layout File

The next step is to add the ViewPager to your layout file for your Activity. This step requires you to dive into the XML of your layout file instead of using the GUI layout editor. Your layout file should look something like this:


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


       <android.support.v4.view.ViewPager

         android:id="@+id/viewpager"

         android:layout_width="fill_parent"

         android:layout_height="fill_parent" />


    </RelativeLayout>

Implementing The Activity

Now we’ll put the main Activity together. The main takeaways from this activity are as follows:

  • The class inherits from FragmentActivity, not Activity
  • This Activity “has a” PageAdapter object and a Fragment object, which we will define a bit later
  • The Activity needs to initialize it’s own PageAdapter

    public class PageViewActivity extends FragmentActivity {

      MyPageAdapter pageAdapter;

      @Override

      public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_page_view);

        List<Fragment> fragments = getFragments();

        pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);

        ViewPager pager = (ViewPager)findViewById(R.id.viewpager);

        pager.setAdapter(pageAdapter);

      }

    }

Implementing The PageAdapter

Now that we have the FragmentActivity covered, we need to create our PageAdapter. This is a class that inherits from the FragmentPageAdapater class. In creating this class, we have two goals in mind:

  • Make sure the Adapter has our fragment list
  • Make sure it gives the Activity the correct fragment

    class MyPageAdapter extends FragmentPagerAdapter {

      private List<Fragment> fragments;


      public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {

        super(fm);

        this.fragments = fragments;

      }

      @Override 

      public Fragment getItem(int position) {

        return this.fragments.get(position);

      }


      @Override

      public int getCount() {

        return this.fragments.size();

      }

    }

Getting The Fragments Set Up

With the PageAdapter complete, all that is now needed are the Fragments themselves. We need to implement two things:

  1. The getFragment method in the PageViewActivity
  2. The MyFragment class

1. The getFragment method is straightforward. The only question is how are the actual Fragments created. For now, we’ll leave that logic to the MyFragment class.


    private List<Fragment> getFragments(){

      List<Fragment> fList = new ArrayList<Fragment>();

     

      fList.add(MyFragment.newInstance("Fragment 1"));

      fList.add(MyFragment.newInstance("Fragment 2")); 

      fList.add(MyFragment.newInstance("Fragment 3"));

     

      return fList;

    }

2. The MyFragment class also has it’s own layout file. For this example, the layout file only consists of a simple TextView. We’ll use this TextView to tell us which Fragment we are currently looking at (notice in the getFragments code, we are passing in a String in the newInstance method).


    <?xml version="1.0" encoding="utf-8"?>

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

      android:layout_width="match_parent"

      android:layout_height="match_parent"

      android:orientation="vertical" >


      <TextView

        android:id="@+id/textView"

        android:layout_width="wrap_content"

        android:layout_height="wrap_content"

        android:layout_centerHorizontal="true"

        android:layout_centerVertical="true"

        android:textAppearance="?android:attr/textAppearanceLarge" />


    </RelativeLayout>

And now the Fragment code itself: The only trick here is that we create the fragment using a static class method, and we use a Bundle to pass information to the Fragment object itself.


    public class MyFragment extends Fragment {

     public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";

     

     public static final MyFragment newInstance(String message)

     {

       MyFragment f = new MyFragment();

       Bundle bdl = new Bundle(1);

       bdl.putString(EXTRA_MESSAGE, message);

       f.setArguments(bdl);

       return f;

     }

     

     @Override

     public View onCreateView(LayoutInflater inflater, ViewGroup container,

       Bundle savedInstanceState) {

       String message = getArguments().getString(EXTRA_MESSAGE);

       View v = inflater.inflate(R.layout.myfragment_layout, container, false);

       TextView messageTextView = (TextView)v.findViewById(R.id.textView);

       messageTextView.setText(message);

     

       return v;

     }

    }

That’s it! with the above code, you can easily get a simple page adapter up and running. You can also get the source code of the above tutorial from GitHub.

For More Advance Developers

There are actually a few different types of FragmentPageAdapters out there. It is important to know what they are and what they do, as knowing this bit of information could save you some time when creating complex applications with the ViewPager. The FragmentPagerAdapter is the more general PageAdapter to use. This version does not destroy Fragments it has as long as the user can potentially go back to that Fragment. The idea is that this PageAdapter is used for mainly “static” or unchanging Fragments. If you have Fragments that are more dynamic and change frequently, you may want to look into the FragmentStatePagerAdapter. This Adapter is a bit more friendly to dynamic Fragments and doesn’t consume nearly as much memory as the FragmentPagerAdapter.
 

Reference: Android Tutorial: Using the ViewPager from our JCG partner Isaac Taylor at the Programming Mobile blog.
Related Whitepaper:

Rapid Android Development: Build Rich, Sensor-Based Applications with Processing

Create mobile apps for Android phones and tablets faster and more easily than you ever imagined

Use 'Processing', the free, award-winning, graphics-savvy language and development environment, to work with the touchscreens, hardware sensors, cameras, network transceivers, and other devices and software in the latest Android phones and tablets.

Get it Now!  

3 Responses to "Android Tutorial: Using the ViewPager"

  1. sowjanya says:

    Great tutorial.

  2. mo says:

    thanks for the tutorial.

    I have two questions though:

    1) if i put:
    Toast.makeText(PageViewActivity.this, “Position: ” + position, Toast.LENGTH_SHORT).show();
    in public Fragment getItem(int position) it shows 0 and 1 for the first fragment, 2 for the second fragment and none for 3rd. it makes me think that it’s not creating the fragments at the right time. is that true? sorry not too familiar with the functions and how they work.

    2) when you finish going through the fragments, and i go back i don’t get the position which means that public Fragment getItem(int position) doesn’t run. why is that?

  3. Kartik says:

    I have followed the steps but in MyPageAdapter.java class the method

    public MyPageAdapter(android.support.v4.app.FragmentManager fm, List fragments)
    {

    super(fm);
    this.fragments = fragments;

    } // the type of Fragmentmanager has been suggested to change to android.support.v4.app

    and

    public android.support.v4.app.Fragment getItem(int position) {

    return this.fragments.get(position);
    } // return methods returns the fragments but the method getItem is not accepting due to mismatch. wn I change the return type to Fragment it gives me error

Leave a Reply


1 × = five



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

15,153 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books
Get tutored by the Geeks! JCG Academy is a fact... Join Now
Hello. Add your message here.