Since then, I think it’s safe to say that most developers have needed to make a ViewPager. Despite how prolific it is, it certainly isn’t the most straightforward widget to include. I think we all have at least once wondered whether we should use a
FragmentPagerAdapter or a
FragmentStatePagerAdapter. Or wondered if we can use a ViewPager without Fragments.
And API confusion aside, we’ve still had long standing, feature requests. RTL support? Vertical orientation? There are numerous open source solutions for these, but nothing official from the support library (now AndroidX)…until now!
Let’s dive in and try to set up ViewPager2! You’ll need your project configured with AndroidX already, as well as supporting minSdkVersion 14 or higher.
The first thing we’ll need to do is add the library to our build.gradle dependencies.
If you’re familiar with RecyclerView, setting up ViewPager2 will be very familiar. We start off by creating an adapter:
1 2 3 4 5 6 7 8 9 10 11
and pair it with a RecyclerView.ViewHolder.
1 2 3 4
Finally, just like RecyclerView, we set the adapter of our ViewPager2 to be an instance of the RecyclerView adapter. However, you’ll note that there’s no need for a LayoutManager.
And with that, we have a working ViewPager2!
We can even set the orientation to scroll vertically with just one line:
Based on the release notes there are a lot of issues left to fix before this moves to a final release – but this is a long awaited update for one of those oldest support library components.