在不滚动的情况下将 ViewPager2 打开到特定位置

Open ViewPager2 to particular position without scrolling

我已经用一些视频 (比如说 10) 实现了 recyclerview。单击任何项​​目都会打开一个 viewpager2 which is on some other activity,其中包含所有项目 and,显示的是单击的项目(来自 recyclerview)。之后,用户只能从那里滚动到其他项目。一切正常。

唯一的问题是当 recyclerview 项目点击时滚动 viewpager2 打开的位置。

只要选择任何项目(第10个)。 viewpager 首先打开,然后滚动到(第 10 个)位置。我想不滚动直接打开viewpager2的第10个位置。任何帮助,将不胜感激。

我试过将当前项目设置为

viewPagerReview.currentItem = recyclerviewItemSelectedPosition

但是如果当前项目是 recyclerview 的最后一个位置,那么 viewpager 也会滚动到最后一个位置。

好的,根据 AndroidDocs 上的 ViewPager2,这就是 setCurrentItem(item: Int) 会做的:

Set the currently selected page. If the ViewPager has already been through its first layout with its current adapter there will be a smooth animated transition between the current item and the specified item.

因此,您需要使用另一种方法,即 setCurrentItem(item: Int, smoothScroll: Boolean) 来指定是否要 smoothScroll

所以,在你的情况下,去:

viewPagerReview.setCurrentItem(recyclerviewItemSelectedPosition, false)

这个问题的正确解法 遵循这种方法 setCurrentItem(item:Int, smoothScroll: Boolean) viewPager.setCurrentItem( 2, 假)