ColonD
ColonD

Reputation: 1034

how do I set the current item programatically in ViewPager2?

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?

Upvotes: 2

Views: 3264

Answers (2)

Ryan M
Ryan M

Reputation: 20137

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.

Upvotes: 3

ianhanniballake
ianhanniballake

Reputation: 199825

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

Upvotes: 5

Related Questions