How to auto-scroll ViewPager2 in Android

How to auto-scroll ViewPager2 in Android

In case you are not aware, Google released ViewPager2 to replace the older and limited ViewPager. This article assumes that you are familiar with the implementation of ViewPager2. However, just to recap, some of the advantages that come with it include:

  • Support for vertical orientation

  • RTL support

  • Since it is built on top of a RecyclerView, you get the added benefit of DiffUtil. I wrote something here that will give you an idea of what the DiffUtil does and why it is good.

To read more on that, then you can do so from the official documentation page here. Today, it is all about how to make ViewPager scrollable in android. Better yet, we will do android-viewpager auto slide in Kotlin and how to show the dots beneath the images to display the current position of the image.

Let us auto scroll ViewPager2

vp1.png

Once you have your setup of the ViewPager2, go ahead and follow the steps below to set up the infinite scrolling.

So the first step is creating two xml files that will be used as dots for an active tab and another for an inactive one. In line with conventions and a nice UI, you should probably set the active dot bigger than the others. See the two layouts below.

active_dot.xml

non_active_dot.xml

One other thing to note is the fact that they are both oval. This is by no means a requirement and you can pick any shape you prefer.

After this, you need to prepare your Activity/Fragment XML layout to show the dots. In this tutorial, I will draw the dots dynamically depending on the size of the image list. So I will just set up a simple layout as shown below. The LinearLayout will be the holder of the dots.

.kt now

In your Activity/Fragment, after setting up the ViewPager2, we need to use the handy ViewPager2.OnPageChangeCallback() to help in keeping track of the current position. The current position receives the active_dot background while the rest are inactive.

To animate the ViewPager, we simply use a Timer to do the work for us.

simple.jpeg

Let us see how you would do this in code.

In onCreate()

The variable slidingImageDots is a list of the dots that we will be creating dynamically in kotlin.

for (i in 0 until slidingDotsCount) {
    slidingImageDots[i] = ImageView(this)
    slidingImageDots[i]?.setImageDrawable(
        ContextCompat.getDrawable(
            applicationContext,
            R.drawable.non_active_dot
        )
    )
    val params =
        LinearLayout.LayoutParams(
            LinearLayout.LayoutParams.WRAP_CONTENT,
            LinearLayout.LayoutParams.WRAP_CONTENT
        )

    params.setMargins(8, 0, 8, 0)
    slider_dots.addView(slidingImageDots[i], params)
}

slidingImageDots[0]?.setImageDrawable(
    ContextCompat.getDrawable(
        applicationContext,
        R.drawable.active_dot
    )
)

val handler = Handler()
val update = Runnable {
    if (currentPage == imagesArray.size) {
        currentPage = 0
    }

    //The second parameter ensures smooth scrolling
    slidingViewPager.setCurrentItem(currentPage++, true)
}

Timer().schedule(object : TimerTask() {
    // task to be scheduled
    override fun run() {
        handler.post(update)
    }
}, 3500, 3500)

As you can see, initially, we set all the dots to inactive except for the first one. After all, once you launch the app, the first image will be the active one. Once you do that, create the timer and start it with the intervals you want.

Notice that in the runnable I have named update checks if the current page is the same as the images array. This would mean that the list is at an end and so we should start to scroll from the start by setting the current page to 0. We also want smooth scrolling so we set it to true.

In the callBack

The callback also follows a similar approach as follows:

private val slidingCallback = object : ViewPager2.OnPageChangeCallback() {
    override fun onPageSelected(position: Int) {
        for (i in 0 until slidingDotsCount) {
            slidingImageDots[i]?.setImageDrawable(
                ContextCompat.getDrawable(
                    applicationContext,
                    R.drawable.non_active_dot
                )
            )
        }

        slidingImageDots[position]?.setImageDrawable(
            ContextCompat.getDrawable(
                applicationContext,
                R.drawable.active_dot
            )
        )
    }
}

All the dots are inactive with the exception of the one in the current position. The result is the image below:

scroll1.jpeg

Wow your users

And just like that, you have a working implementation of a continuous ViewPager in android. Find the full code below.

Until next time!

PS: Let us connect on GitHub, Twitter, and LinkedIn.