Posted on

Android ViewPager


android viewpager

Designed by Freepik

Android ViewPager is made for displaying multiple fragments with a swipe as a navigation across them. In this tutorial, we’re going to go through the process using ViewPager

 

Fragments

The first thing you need to add is several fragments. They’re just going to display TextView’s with different strings, but you can display the same fragment and change content depending on the position in the list

fragment_first.xml

FirstFragment.java

And second fragment, fragment_second.xml

SecondFragment.java

ViewPager Adapter

I always extend FragmentStatePagerAdapter

Initialize ViewPager

Now finally let’s add ViewPager to out activity_main.java

And set it up in MainActivity.java

Off Screen Limit

The way ViewPager works is it creates the fragment you’re currently in, 1 to the left and one to the right (ofScreenLimit default attrite of 1)

Creating fragments, loading images, even if there’s stored locally takes time. If you want that smooth experience, like they have in app’s intro – you better have all those fragments having created. This approach is ok if you don’t have a lot of fragments

Access Fragments

Sometimes you want to retrieve¬†fragments on the exact position. Unfortunately, pager adapter doesn’t provide this feature by default. There’s a method called FragmentStatePagerAdapter#getItem,¬†but it’s the one implementation you provided above and it will return a newly created fragment.

What you need is to change adapter code a bit

everything works the same, but this way you have the access to the list of initialized fragments. Then you can just call

 

 

That’s basically it, I think it covers most of the Android ViewPager use cases. If you want to check some cool animations during swipe that you can implement with ViewPager – check this post

 

Don’t forget to subscribe, follow me on Facebook, Twitter and G+ to get notified about the latest posts!