Created
March 26, 2021 06:33
-
-
Save joyceHong0524/e4f543b62e8ace426b4af04263a4106a to your computer and use it in GitHub Desktop.
Viewpager2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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