how do I set the current item programatically in ViewPager2?

Viewed 1474

So in the the old ViewPager, you could set the initial position of the ViewPager using

viewPager.setCurrentItem(x)

How do you do that in ViewPager2?

2 Answers

setCurrentItem is also an API on ViewPager2, so you should use that.

It works the same way in ViewPager2: setCurrentItem(int).

But do note the caveat mentioned in the docs:

Silently ignored if the adapter is not set or empty.

You may be calling it before setting the adapter, or before adding data to the adapter. Ensure that the adapter is set and populated with data before calling setCurrentItem.

Related