ViewPager2 default position
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)
Do not use timers, you will run into a lot of probable states in which the user has a slow phone and it actually takes a lot longer than 100 ms to run, also, you wouldn't want too slow of a timer making it ridiculously un-reliable.
Below we do the following, we set a listener to our ViewTreeObserver and wait until a set number of children have been laid out in our ViewPager2's RecyclerView (it's inner working). Once we are sure x number of items have been laid out, we start our no-animation scroll to start at the position.
val recyclerView = (Your ViewPager2).getChildAt(0)recyclerView.apply { val itemCount = adapter?.itemCount ?: 0 if(itemCount >= #(Position you want to scroll to)) { viewTreeObserver.addOnGlobalLayoutListener(object: ViewTreeObserver.OnGlobalLayoutListener { override fun onGlobalLayout() { viewTreeObserver.removeOnGlobalLayoutListener(this) // False for without animation scroll (Your ViewPager2).scrollToPosition(#PositionToStartAt, false) } }}