Skip to content

Instantly share code, notes, and snippets.

@prabhatsdp
Created February 24, 2022 08:10
Show Gist options
  • Save prabhatsdp/6dc8578c63c1dcb072b4658d533bc2c7 to your computer and use it in GitHub Desktop.
Save prabhatsdp/6dc8578c63c1dcb072b4658d533bc2c7 to your computer and use it in GitHub Desktop.
ViewPager auto scroll logic
// before onCreate() in acivity/fragment
private val mainHandler = Handler(Looper.getMainLooper())
private val updateBannerItemTask = object : Runnable {
override fun run() {
updateCurrentBannerItem()
mainHandler.postDelayed(this, 3000)
}
}
// call this function after pages (in oncreate or onViewCreated) loads
// images is the list of viewpager
private fun startSlideShow() {
if (pages.isEmpty()) return
mainHandler.postDelayed(updateBannerItemTask, 3000)
}
// define this function somewhere in the screen
private fun updateCurrentBannerItem() {
val currentItem = if (binding.viewPager.currentItem == pages.size - 1) 0 else binding.viewPager.currentItem + 1
binding.viewPager.setCurrentItem(currentItem, true)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment