ViewPager with auto scroll

Function

The function uses a Handler and Runnable to repeat the code snippet to change the current item with a time interval it receives as a parameter.

fun ViewPager.autoScroll(interval: Long) {

val handler = Handler()
var scrollPosition = 0

val runnable = object : Runnable {

override fun run() {

/**
* Calculate "scroll position" with
* adapter pages count and current
* value of scrollPosition.
*/
val count = adapter?.count ?: 0
setCurrentItem(scrollPosition++ % count, true)

handler.postDelayed(this, interval)
}
}

addOnPageChangeListener(object: ViewPager.OnPageChangeListener {
override fun onPageSelected(position: Int) {
// Updating "scroll position" when user scrolls manually
scrollPosition = position + 1
}

override fun onPageScrollStateChanged(state: Int) {
// Not necessary
}

override fun onPageScrolled(
position: Int,
positionOffset: Float,
positionOffsetPixels: Int
) {
// Not necessary
}
})

handler.post(runnable)
}

How to use it

Only imports the function and call it using the ViewPager reference.

private fun setViewPager() {
viewPager.adapter = adapter

/**
* Start automatic scrolling with an
* interval of 3 seconds.
*/
viewPager.autoScroll(3000)
}

Github

https://github.com/Atsz7/ViewPagerAutoScroll

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store