Search code examples
androidandroid-viewpager2

ViewPager2 default position


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)

Solution

  • 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)