Saturday, July 23, 2011

ViewPager example from PAUG

During a recent session at the Paris Android User Group (hi PAUG!) we did a live coding of a ViewPager example, it took around 5 minutes. What is a ViewPager? It is a tasty new class smothered in awesome sauce on a bed of rocking adapters, seriously I think I may use at least one in every Android app I make from now on. It was released as part of the updated Compatibility Package.

White on green was a great choice, right? very.... visible.

If you search for 'android view pager' you'll see many questions on how to implement smooth, finger tracking, horizontal view paging in Android, so it seems appropriate the solution is called ViewPager. ViewPager was launched at the end of last week as part of the updated Compatibility package and supports Android 1.6+.

Some of you may have been aware of the Workspace example open sourced with the I/O Sched app. An important difference between ViewPager and Workspace is that ViewPager pulls its views from an adapter, so like with a ListView as the items are slid off the screen they can be recycled and/or brought back in on the right side of the screen. The sample code for ViewPager shows this being done with a FragmentPagerAdapter, where each view is a fragment, giving you an amazing amount of control over your application.

In this example we are just sliding TextViews on and off the screen, here is the complete guide:

1) Download the update from Android SDK & AVD manager: Available Packages -> Android Repository -> Android Compatibility Package, revision 3. It will be installed in \extras\android\compatibility\v4

2) Create a new Android Project (I'm using Eclipse) and include the library. Properties -> Java Build Path -> Libraries -> Add External JARs -> android-support-v4.jar, it is in the install directory.
Update: As Thomas says if you're using the latest ADT you can now just right-click on your project -> Android Tools -> Add Compatibility Library

3) Your should now be able to use ViewPager in your Activity

4) If you use ViewPager in an xml layout, be sure to use the full reference, e.g.

<android.support.v4.view.ViewPager
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="@+id/awesomepager"/>


5) Create a PagerAdapter to serve up your Views to the ViewPager. The key methods to implement are getCount(), instantiateItem(), destroyItem() and isViewFromObject() here are my implementations along with some JavaDoc from the source.

Note: It is up to the developer to add the views they are creating in instantiateItem() to the collection being passed in. The converse applies to destroyItem(), you must remove the item from the collection. The collection in this example is the ViewPager that is using the PagerAdapter.

The complete project source is at http://code.google.com/p/viewpagerexample/

A more professional and complete example can be found in the Compatibility Package samples (in the install directory), where a FragmentPagerAdapter implementation is provided. Using fragments inside a ViewPager can provide much better structure to an application as each view has its own FragmentActivity.

43 comments:

Eyal LEZMY said...

Hey Richard,

VERY interesting post to bookmark !

Hi from the Paris Android User Group team ;o)


http://paug.fr

npincon said...

Very interesting. Thanks a lot Richard!

TomTasche said...

"3) Your Activity should now be able to extend ViewPager" confused me at first.

Thanks for the tutorial
Tom

TomTasche said...

"2) Create a new Android Project (I'm using Eclipse) and include the library. Properties -> Java Build Path -> Libraries -> Add External JARs -> android-support-v4.jar, it is in the install directory." since ADT 12 it's as easy as right-clicking your project -> Android Tools -> Add Compatibility Library. :)

Tom

k7k0 said...

Hi. Any idea how to give support to Android 1.5 users? We still have a lot of them!

Unknown said...

No, unfortunately the Compatibility Package doesn't work with Android 1.5

It looks like the Workspace from i/o sched doesn't support 1.5 either.

Unknown said...

And thanks Thomas! I'll update the post accordingly.

TomTasche said...

Thanks for updating your post, Richard!

Do you have an idea how to get WebViews and ViewPager to play nicely together? I tried using WebViews in your example, but it didn't work.
I guess they are interfering each other because they both "scroll" somehow.

Have a great day
Tom

Unknown said...

I'll be doing a follow up blog post, I'll try and get webviews into that. Seems quite important.

TomTasche said...

Great! Thank you. :)

Peter said...

Hi, do you know how to reload the ViewPager in the same Class ?

Anonymous said...

I really liked the article, and the very cool blog

Vince said...

Hi,

I've already tried to use ViewPager (successfully by the way) but I wanted to know if there will be a standard "ViewPagerBar" with the labels like it is done on the Google+ app ?

Thanks.

Unknown said...

all I can say is that there isn't one at the moment but I'd love to see one as well, lots of people are asking for it. There are already a few 3rd party ones around ViewPagerIndicator etc.. sorry I can't be more helpful

Anonymous said...

I really liked the article, and the very cool blog

Unknown said...

If there is a captcha on my blog then it is provided by blogger, I haven't done anything special.

anji said...

Thanks Paug. I am using ViewPager and PagerAdapter with web views in my application. Your code was very helpful. What is ViewPager.SavedState for? The documentation for it doesnt explain much.I want the ViewPager to show the same page on rotation. I tried saving the position of page and then using myPager.setCurrentItem() to the saved position but this doesn't help. How to i save the state of ViewPager on rotation?

pramod said...

I have to create 3X3 array of images with text like grid view using viewpager.which should scroll horizontally.

Anonymous said...

*,very nice page, i certainly enjoy this website, keep on it, keeping on!
xyzrxyz.2011

De volta para o passado said...

Hi, Richard.

I am a Master's student and I'm search by Android portability issues (mainly about several devices) and how a SPL can help to resolve it.

Searching the web, I'm on your blog.

Can you help me, indicanting some link, articles, documentation etc? And tell me what you think about it?

Thank you.

--
Adorilson

Anonymous said...

brinkka2011 says: Sick! Just obtained a brand-new Pearl and I can now read your blog on my phone's browser, it didn't get the job done on my aged one.

Unknown said...

Excellent post! I greatly enjoyed it. I am now in the process of replacing my tired old Gallery of Views with a ViewPager in my app thanks to this post.

It is working beautifully, but there is one piece that I haven't been able to figure out. The Android Market (which you cite as a ViewPager example) displays a solid black divider between the views. How is this being accomplished? An XML attribute on the ViewPager?

Anonymous said...

brinkka2011 says: *,very nice page, i certainly enjoy this website, keep on it, keeping on!

Unknown said...

Hey Andrew, it is a good point. I used Market as an example of what a ViewPager looks like, but I don't know if it is actually using ViewPager. I don't know of a way of getting the black lines, maybe by changing the source or ViewPager,

Anonymous said...

brinkka2011 says: Im speechless. This is a superb blog and very enticing too. Great work! Thats not in point of fact so much coming from an amateur publisher like me, however its all I may say after diving into your posts. Nice grammar and vocabulary. No longer like other blogs. You really recognize what you?re speaking approximately too. So much that you just made me want to explore more. Your weblog has grow to be a stepping stone for me, my friend.

David said...

Hi, I am really interested in your blog posting and ViewPager is exactly what I want.

However when I go to the link for the source code there is nothing there.

Am I missing something?

Dominik said...

Thanks for that tutorial. I could successfully replicate it with your instructions.

I have a question. How can I display Activities instead of the TextViews with this?
I have 3 different Activities I want to include in this sliding mechanism but I don't know how to do it. I think I have to change the activities to views, right? But my layouts are all in XML files.
Please help.

bob420 said...

Hey Richard,

I saw this post and the one o you did on the Google Developers Blog about ViewPager and I was wondering if it's possible to extend the ViewPager to make it behave as an infinite loop widget.
Can you point me in the right direction to get it done?

Thanks!
Felipe

Unknown said...

E-Nature - The best way would be to wrap them as Fragments and use the Fragment Pager

Unknown said...

bob420 you need to check the source code for the ViewPager, it is in your Android-sdk directory on your computer, then see if you can change it to loop back to page 0 at the end.

sathish moodambail said...

Hey Richard,
I have some issues in using the ViewPager in actionbar tabs. I have page with five tabs, when select the first tab using ViewPager I select the first page by creating Fragments , but it is actually creating first and second page fragments. Is there any way to avoid creation of second fragments when I select the first page using ViewPager?

MRK said...

i want to View Pager Example...
I not found Proper example in ur blog
Can u send me View Pager example....
Thanks

Anonymous said...

hey paug, I implemented an ViewPager. It switches between 3 Linear Layouts. but now it seems that my buttons don't work probably. they become instantiated, because they are not null, but if i click them nothing happens anymore.

any suggestions?

innocence said...

AwesomeViewPager is Awesome!!


Any hint on how to use the horizontally scrolling titles of the tabs (or the pages) on top of ViewPager? they move as user flicks the ViewPager

Unknown said...

@innocence, search the web for ViewPagerIndicator. It is an unofficial extension to the ViewPager used to add that indicator strip above the ViewPager.

Flo (Living Rooms Developers) said...

Great feature and thank you very much for the tutorial!

It gave us a perfect kick-start for our latest Android App named RVG-Assistent...

Anonymous said...

Thanx a lot

Nanjou said...

Hi. Nice tutorial thanks a lot!
I've contacted you there is no much time on twitter as @BeMadDude ^^
I was wondering if is it possible to add a Vertical swipe, it could be interesting ! Have you any idea about this custom component ?

Thanks.

Unknown said...

i am unable to get the project to be downloaded.
can u provide me a sample project please.

Unknown said...

Hi Sharath, you can check the source out with an SVN client anonymously at http://code.google.com/p/viewpagerexample/source/checkout

or you can browse the source and download each file http://code.google.com/p/viewpagerexample/source/browse/#svn%2Ftrunk%2FAwesomePager

The main file download is at http://viewpagerexample.googlecode.com/svn/trunk/AwesomePager/src/com/geekyouup/paug/awesomepager/AwesomePagerActivity.java

Unknown said...

Thanks for your very instructive example. I got it working with a custom view class, but then decided that I wanted to use it with a surfaceview and ran into some problems with it lagging on the transition. I was hoping that you might be able to point me in the right direction. I wrote up the question here: http://stackoverflow.com/questions/11389302/surfaceview-with-viewpager-in-api-level-10-has-a-long-delay-during-a-new-transit

Unknown said...

Hi,this is good and i need the programmatic way of Viewpager.Thanks in advance

Unknown said...

I saw this publish and the one o you did on the Search engines Designers Weblog about ViewPager and I was thinking if it's possible to boost the ViewPager to create it act as an unlimited cycle gadget.