安卓:ViewPager2速度可控地翻页一次代码
fun ViewPager2.startFakeScroll() {
if (!this.beginFakeDrag()) return
val animator = ValueAnimator.ofFloat(0f, -this.width.toFloat())
animator.duration = 400
animator.interpolator = LinearInterpolator()
var lastValue = 0f
animator.addUpdateListener {
val currentValue = it.animatedValue as? Float ?: return@addUpdateListener
val delta = currentValue - lastValue
this.fakeDragBy(delta)
lastValue = currentValue
}
animator.addListener(object : AnimatorListenerAdapter() {
override fun onAnimationEnd(animation: Animator) {
this@startFakeScroll.endFakeDrag()
}
})
animator.start()
}