Skip to content

Instantly share code, notes, and snippets.

@joyceHong0524
Created March 26, 2021 06:33
Show Gist options
  • Save joyceHong0524/e4f543b62e8ace426b4af04263a4106a to your computer and use it in GitHub Desktop.
Save joyceHong0524/e4f543b62e8ace426b4af04263a4106a to your computer and use it in GitHub Desktop.
Viewpager2
fun ViewPager2.setCurrentItemWithDuration(
item: Int,
duration: Long,
interpolator: TimeInterpolator = AccelerateDecelerateInterpolator(),
pagePxWidth: Int = width // Default value taken from getWidth() from ViewPager2 view
) {
val pxToDrag: Int = pagePxWidth * (item - currentItem)
val animator = ValueAnimator.ofInt(0, pxToDrag)
var previousValue = 0
animator.addUpdateListener { valueAnimator ->
val currentValue = valueAnimator.animatedValue as Int
val currentPxToDrag = (currentValue - previousValue).toFloat()
fakeDragBy(-currentPxToDrag)
previousValue = currentValue
}
animator.addListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator?) { beginFakeDrag() }
override fun onAnimationEnd(animation: Animator?) { endFakeDrag() }
override fun onAnimationCancel(animation: Animator?) { /* Ignored */ }
override fun onAnimationRepeat(animation: Animator?) { /* Ignored */ }
})
animator.interpolator = interpolator
animator.duration = duration
animator.start()
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment