I have some animations in my Android app and I'd like to change my code in order to take advantage of Android KTX. Sadly, I don't really understand the documentation about it. Could someone tell me how I can improve this code with the help of Android KTX?
view
.animate()
.translationY(view.height.toFloat())
.setDuration(3000)
.setInterpolator(AccelerateInterpolator())
.setListener(object : Animator.AnimatorListener {
override fun onAnimationStart(animation: Animator?) {}
override fun onAnimationRepeat(animation: Animator?) {}
override fun onAnimationCancel(animation: Animator?) {}
override fun onAnimationEnd(animation: Animator?) {
// Do whatever I want
}
})
Of course, I have already added the dependency in my Gradle file:
implementation 'androidx.core:core-ktx:1.0.2'
Thank you very much in advance :)
Android KTX has doOnEnd { /** Do whatever you want **/ }
and other extension functions for android.animation.Animator
. When you call view.animate()
, it returns ViewPropertyAnimator
which is not inherited from android.animation.Animator
class. Therefore you cannot view.animate().doOnEnd { /** Do whatever you want **/ }
provided by Android KTX.
However, you can use withEndAction to do anything when animation ends. withEndAction
is part of default ViewPropertyAnimator
, so, you do not need to have Android KTX to use that:
view
.animate()
.translationY(image.height.toFloat())
.setDuration(3000)
.setInterpolator(AccelerateInterpolator())
.withEndAction {
// Do whatever you want
}