I'm creating a slideshow with ViewPager2. For example, the slideshow has 3 items and I want to show the second item when the activity opens. I use setCurrentItem(int item, boolean smoothScroll)
method but it doesn't work and nothing happens. How can I achieve it?
viewPager.adapter = adapter viewPager.setCurrentItem(1, true)
ViewPager2 is an improved version of the ViewPager library that offers enhanced functionality and addresses common difficulties with using ViewPager . If your app already uses ViewPager , read this page to learn more about migrating to ViewPager2 .
As we already know that ViewPager2 is built on RecyclerView that's why it's easy to update only one item by calling the method notifyItemChanged(index). If we want to update all items then we can also do this by simply calling the notifyDatasetChanged() method. That's it for now.
Establish the link by creating an instance of this class, make sure the ViewPager2 has an adapter and then call attach() on it. Instantiating a TabLayoutMediator will only create the mediator object, attach() will link the TabLayout and the ViewPager2 together.
I think an easier more reliable fix is to defer to next run cycle instead of unsecure delay e.g
viewPager.post { viewPager.setCurrentItem(1, true) }
setCurrentItem(int item, boolean smoothScroll)
works correctly in ViewPager
but in ViewPager2
it does not work as expected. Finally, I faced this problem by adding setCurrentItem(int item, boolean smoothScroll
) method into a delay like this:
Handler().postDelayed({ view.viewPager.setCurrentItem(startPosition, false) }, 100)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With