First Glance at new Viewpager2 in Android
Exploring ViewPager2 in Android
using recyclerview adapter with viewpager
We all know how effective recyclerview in loading a list of views. Imagine how useful bringing that robust functionality to view-pager and that’s what view-pager2 is all about.
At some point in time as a mobile developer, we all have to implement swipe-able layout which shows different views or fragments while swiping. Until now we have used view-pager to achieve this, now it’s time to upgrade, the android team has announced the viewpager2 the combination of original view-pager functionality and recyclerview.
Before we start on how to use viewpager2 let me be clear that viewpager2 is still in beta iterations soon stable version is going to be released. That being said let’s start coding
Integration
Viewpager2 is a support library that means we just need to add the following line under the dependencies tag in build.gradle file
implementation "androidx.viewpager2:viewpager2:1.0.0-beta05"
Check here for latest versions
XML code
It is pretty same as viewpager, have a look
<androidx.viewpager2.widget.ViewPager2
android:layout_width="match_parent"
android:layout_height="0dp"
android:background="@color/colorWhite"
android:id="@+id/viewpager"/>
Listeners
Here we add a callback that will be invoked when the views are scrolled, have a look
onPageScrolled
This method will be invoked when the current page is scrolled, it might be initiated by the user or programmatically
onPageScrollStateChanged
This method will be invoked at various stages while scrolling with a flag that indicates the current scrolling status.
onPageSelected
This method will be invoked when a new page becomes selected.
Adapter
This is where the major change comes in, here we use our lovely recyclerview adapter instead of PagerAdapter. Have a look
This is a very normal recyclerview adapter that works with new viewpager2. let’s see how we can use it
Does it seem familiar, yes, it is the same as the recyclerview process. This is great right we don’t need any extra knowledge to use viewpager2. Now, what’s even better is that we can apply orientations too.
Orientations
Similar to recyclerview we have orientations in viewpager2 which results in the scrolling in either HORIZONTAL or VERTICAL. The Android team had made very easy to implement have a look
viewpager2.orientation = ViewPager2.ORIENTATION_HORIZONTALorviewpager2.orientation = ViewPager2.ORIENTATION_VERTICAL
That’s all it takes to implement the orientation in viewpager.
Viewpager2 with TabLayout
As we all know the viewpager with tablayout is one of the killer option to create a perfect UI. Now, let’s see how to use tab layout with viewPager2. Starting with XML code for tablayout and viewpager
Now let’s see the coding part, honestly, coding part is way easier than layout, in this case, 😜 have a look
Have a look at how orientations and tab-layout works with viewpager2

