2

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?

ColonD
  • 954
  • 10
  • 28
  • 1
    Does this answer your question? [ViewPager set current page programmatically](https://stackoverflow.com/questions/28968512/viewpager-set-current-page-programmatically) – Yabaze Cool Aug 12 '20 at 04:32
  • 1
    @YabazeCool no, that one is for the old ViewPager. My question has been handled answered below, but thanks anyways! – ColonD Aug 12 '20 at 05:15
  • 1
    [Migration Guide from ViewPager to ViewPager2][1] [Reference Demo][2] here also they are using `viewPager.setCurrentItem(position);`. [1]: https://developer.android.com/training/animation/vp2-migration [2]: https://developer.android.com/training/animation/screen-slide-2#viewpager – Yabaze Cool Aug 12 '20 at 10:34
  • Yes, I got that. some weird bug in android studio was showing the method in red so i thought the method was changed. but restarting the thing seemed to work – ColonD Aug 13 '20 at 06:29

2 Answers2

4

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

ianhanniballake
  • 191,609
  • 30
  • 470
  • 443
3

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.

Ryan M
  • 18,333
  • 31
  • 67
  • 74