如何调整ViewPager2滚动速度?旧ViewPager适配代码失效求助
如何修改ViewPager2的滚动速度
当然可以调整ViewPager2的滚动速度!它和旧版ViewPager的实现逻辑完全不同——ViewPager2底层是基于RecyclerView构建的,所以之前针对旧ViewPager的反射修改方法自然就失效了。下面是具体的实现方案:
核心思路
ViewPager2的滚动行为由其内部的RecyclerView.LayoutManager控制,我们需要自定义一个支持自定义滚动速度的LayoutManager,替换掉默认的实现。
具体步骤
自定义SmoothScroller
首先创建一个继承自LinearSmoothScroller的类,重写calculateSpeedPerPixel方法来控制滚动速度:class CustomSmoothScroller(context: Context) : LinearSmoothScroller(context) { // 这里的数值可以根据需求调整,值越大,滚动速度越慢 private val SPEED = 0.02f override fun calculateSpeedPerPixel(displayMetrics: DisplayMetrics?): Float { return SPEED / (displayMetrics?.density ?: 1f) } }自定义LayoutManager
接着自定义一个LinearLayoutManager(因为ViewPager2默认用的是这个),重写createSnapScroller方法,返回我们刚才定义的CustomSmoothScroller:class CustomLayoutManager(context: Context, orientation: Int) : LinearLayoutManager(context, orientation, false) { override fun createSnapScroller(context: Context?): SmoothScroller? { return context?.let { CustomSmoothScroller(it) } } }给ViewPager2设置自定义LayoutManager
最后在代码里把这个自定义的LayoutManager设置给你的ViewPager2:// 横向滚动的ViewPager2就传LinearLayoutManager.HORIZONTAL,纵向则传VERTICAL val customLayoutManager = CustomLayoutManager(this, LinearLayoutManager.HORIZONTAL) viewPager2.layoutManager = customLayoutManager
小提示
calculateSpeedPerPixel方法的返回值是每像素滚动所需的时间(秒),所以数值越大,滚动相同距离的时间越长,视觉上速度就越慢;反之数值越小,滚动速度越快。- 如果你的ViewPager2是纵向滚动的,记得在创建CustomLayoutManager时传入
LinearLayoutManager.VERTICAL。
内容的提问来源于stack exchange,提问作者Skullper
相关产品推荐
相关产品推荐

