Open SourceAdd Horizontal Paging To Your Android Applications

Add Horizontal Paging To Your Android Applications

Developer.com content and product recommendations are editorially independent. We may make money when you click on links to our partners. Learn More.

Horizontal Paging functionality is a popular user interface (UI) technique added to the latest Android Compatibility Package. In fact, horizontal paging has been popping up in popular Android applications such as the Android Market application and the new Google+ Android client. Swiping left and right to change screens of similar content also received coverage for being a broadly supported navigational element in Android 4.0 (Ice Cream Sandwich).

Although not part of the Android SDK, this UI functionality has been included as part of the latest Android Compatibility Package (introduced in release 3 of the V4 package), and can be used with Activity-based and fragment-aware applications. Any developers who are ready to use the Android Compatibility Package can implement horizontal paging. In this short tutorial, learn how to incorporate horizontal paging or swiping into your Android applications quickly and easily.

The What and How of Android Horizontal Paging

From a user perspective, horizontal paging is simple. An Android application with horizontal paging support simply has screens or “pages” that the user can swipe (left or right) to view. The number of pages and the content of each page is up to the developer.

For example, the Android Market enables horizontal paging to navigate the apps available on the market. The Google+ client uses them to page between nearby, circles, and incoming posts, as shown in the following screenshot.

Google+ Client Using Horizontal Paging

As a developer, you can enable horizontal paging within your own applications using some classes included in the Android Compatibility package. First, there is a new user interface control called a ViewPager, which you can include in your layout resource files. Much like a Gallery control, the ViewPager is the container that holds your page contents. And like a Gallery control, its contents can be populated using a special data adapter. For basic page contents, you can simply extend the PageAdapter class to populate the ViewPager control with the contents of your choice.

The developer controls the page contents served up into the ViewPager control. As its name implies, each page displays a View. A View can be simple, like a TextView control with certain textual contents, or a more complex control like a TableLayout filled with child view controls, or an entire view hierarchy as defined in a layout resource file.

How Do I Access the Android Horizontal Paging Classes?

The ViewPager and PageAdapter classes are part of the Android Compatibility package, which can be downloaded using the Android SDK and AVD Manager.

A quick note about naming: With the recent update in Eclipse to R14 of the tools, the SDK and AVD managers were split apart. Use the Android SDK Manager. In addition, the Android Compatibility package, while still named as such inside Eclipse, is now being called the Android Support package. Given there are features of it that don’t exist within the stock APIs this is a more descriptive name. However, we continue to refer to it as the Android Compatibility package.

If you are using Eclipse, recent versions of the ADT plug-in have added the ability to easily add the package to your existing Android project. To do this, right-click on your project in the Project Explorer, choose Android Tools, and select Add Compatibility Library (Figure 2). A file called android-support-v4.jar file will appear in your Referenced Libraries project folder and you can begin using the classes.

Select "Add Compatibility Library" from Android Tools

A Quick Android Horizontal Paging Example

Let’s show a quick example of how to create a three-page ViewPager control. To do so, follow these steps:

  1. Create a new Android project in Eclipse, or choose to modify an existing one.
  2. Add the Android Compatibility package to the project as described above.
  3. Create three layout resource files, one for each page in your ViewPager control. For example, for the sample application we created three layouts, each with a TextView and an ImageView (as shown in Figure 3).

    Three Layouts for Sample App

  4. Update the main.xmllayout file and include a ViewPager control. This control must be defined using its fully qualified control name. Here’s an example:

    android:orientation="vertical"

    android:layout_width="fill_parent"

    android:layout_height="fill_parent">

    android:layout_width="match_parent"

    android:layout_height="match_parent"

    android:id="@+id/threepageviewer"/>
  5. Update the Activity class and implement a custom PagerAdapter class. You will need to implement several important data adapter methods for this class. The getCount() method must return the number of pages for the ViewPager (in this case, three). The instantiateItem() method must inflate the appropriate view control for each page (in our example, a full layout), populate it with any data, as determined by the page position, and add it to the collection used by the ViewPager control. With a three page layout, we have defined the left layout as position 0, the middle layout as position 1, and the right layout as position 2.
  6. Finally, you’ll need to implement the destroyItem() method to remove each page’s contents when it is no longer being displayed.

Here’s a sample implementation of a custom PagerAdapter class:

private class MyPagerAdapter extends PagerAdapter {

public int getCount() {

return 3;

}

public Object instantiateItem(View collection, int position) {

LayoutInflater inflater = (LayoutInflater) collection.getContext()

.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

int resId = 0;

switch (position) {

case 0:

resId = R.layout.left;

break;

case 1:

resId = R.layout.middle;

break;

case 2:

resId = R.layout.right;

break;

}

View view = inflater.inflate(resId, null);

((ViewPager) collection).addView(view, 0);

return view;

}

@Override

public void destroyItem(View pager, int arg1, Object view) {

((ViewPager) pager).removeView((View) view);

}

}

You need to update the onCreate() method of your Activity class to bind your custom PagerAdapter to the ViewPager control you defined in your Activity layout resource file, main.xml. You set the data adapter using the setAdapter() method. You can also modify the default starting position of the ViewPager, so that the Monkey (position 1, the middle page) is the default using the setCurrentItem() method.

@Override

public void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.main);

MyPagerAdapter adapter = new MyPagerAdapter();

ViewPager myPager = (ViewPager) findViewById(R.id.threepageviewer);

myPager.setAdapter(adapter);

myPager.setCurrentItem(1);

}

That’s all there is to it. Now you’ve got a three-page horizontal paging screen, as shown in Figure 4, that loads the middle page by default (the monkey). The user can swipe or page to the left to see the lion page or right to see the rhino page.

A Three-page Horizontal Paging Screen in Android

The source code is available for download.

What About Fragments?

Got an application that relies upon fragments? No problem! There’s nothing stopping you from using fragments as your ViewPager control page contents. Take a look at the FragmentPagerAdapter for this very purpose and serve up fragment-based pages.

Conclusion

Android users desire applications that have easy-to-navigate user interfaces. The horizontal paging functionality, available within the Android Compatibility package, gives application developers yet another handy technique for displaying substantial quantities of information in such a fashion. Whether your application is fragment-ready or not, you can use the ViewPager and related data adapter classes available to create dynamic user interfaces for your users.

About the Authors

Shane Conder Shane Conder and Lauren DarceyContributing Editors, Mobile Development–have coauthored two books on Android development: an in-depth programming book entitled Android Wireless Application Development (ISBN-13: 978-0-321-62709-4) and Sams Teach Yourself Android Application Development in 24 Hours (ISBN-13: 978-0-321-67335-0). When not writing, they spend their time developing mobile software at their company and providing consulting services.

Email | Blog | Twitter

Lauren Darcey

Get the Free Newsletter!

Subscribe to Developer Insider for top news, trends & analysis

Latest Posts

Related Stories