Created
February 24, 2022 08:10
-
-
Save prabhatsdp/6dc8578c63c1dcb072b4658d533bc2c7 to your computer and use it in GitHub Desktop.
ViewPager auto scroll logic
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// 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