虽然大多数人报告滚动不顺畅,但我在这里报告相反的情况。
我想滚动到我的viewpager的中间,没有任何滚动动画。应该尽快。这是我的初始活动人群所必需的。
根据文档,我可以使用
smoothScroll
参数并将其设置为 false
。
/**
* Set the currently selected page. If {@code smoothScroll = true}, will perform a smooth
* animation from the current item to the new item. Silently ignored if the adapter is not set
* or empty. Clamps item to the bounds of the adapter.
*
* @param item Item index to select
* @param smoothScroll True to smoothly scroll to the new item, false to transition immediately
*/
public void setCurrentItem(int item, boolean smoothScroll)
但这实际上并没有做出任何改变,并且滚动动画是可见的。
有人有同样的问题并且知道如何解决吗?我正在使用 Kotlin + ViewPager2
这条评论引导我走向正确的道路。
当您在 viewpager 上使用
.post {}
调用该方法时,它会按预期工作。
viewPager.post {
viewPager.setCurrentItem(desiredPosition, false)
}
而且我不认为这是像评论作者建议的那样的黑客行为,所以我会同意它:)
如果您有其他意见,我很乐意在这里!
我尝试使用这个解决方案,它的工作原理很神奇,我只是使用 viewPager 作为 recyclerView (它具有 mRecyclerView 属性),使用以下扩展函数:
fun ViewPager2.scrollToPage(page:Int) {
val recyclerViewField = ViewPager2::class.java.getDeclaredField("mRecyclerView")
recyclerViewField.isAccessible = true
val recyclerView = recyclerViewField.get(this) as RecyclerView
recyclerView.scrollToPosition(page)
}