Oct 25, 2012

Examining the ViewPager #2

This article is part of a series of articles about the ViewPager component. Click here to see a list of all articles of this series.

Offscreen pages

The ViewPager doesn't create all its pages at once. When using a lot of pages this would be horribly slow and even unnecessary if the user would never swipe through all these pages. By default the ViewPager only creates the current page as well as the offscreen pages to the left and right of the current page.

If you only use a small amount of pages you may get a better performance by creating them all at once. You can use setOffscreenPageLimit(int limit) to set the number of pages that will be created and retained. Note that the limit applies to both sides of the current page. So if you set the offscreen page limit to 2 the ViewPager will retain 5 pages: The current page plus 2 pages to the left and right.

Responding to changing states

You can get notified whenever the displayed page changes or is incrementally scrolled. To listen to these state changes you can implement the OnPageChangeListener interface or extend the SimpleOnPageChangeListener class if you do not intent to override every method of the interfacce.

The following example listener updates the title of the activity according to the title of the currently selected page:


Margin between pages

When scrolling through pages they all look like glued together. You can use setPageMargin(int pixels) to define a margin between pages. The gap is filled with the background color of the ViewPager.

The following screenshots are showing the same ViewPager during switching pages. The left screenshot shows the ViewPager with no page margin set. In the right screenshot the margin has been set to 20 pixels. Notice that the method expects the margin to be defined in pixels. To use the same physical margin on all kind of screens independent from their pixel density define the margin in density independent pixels (dp) and convert them to the actual number of pixels for the current screen.

It's also possible to define a drawable that will be used to fill the margin between two pages using setPageMarginDrawable(int resId) or setPageMarginDrawable(Drawable d). The best approach is to use a Nine-patch that be scaled dynamically by the system to fill the space between the pages.

Switching pages programmatically

You can also switch between pages programmatically. Using setCurrentItem(int position, boolean smoothScroll) you can switch to the given position. If the second parameter is true a smooth animated transition is being performed. Using false the ViewPager will switch to the given page without any animation. If you always want to switch pages with an animation you can also leave the second parameter and use setCurrentItem(int position).

1 comment:

  1. This comment has been removed by a blog administrator.