Android animation with KTX

2.4k Views Asked by At

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 :)

2

There are 2 best solutions below

0
On BEST ANSWER

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
    }
0
On

Android KTX provides some animation event listener functions for Animator instances. As view.animate() returns an instance of ViewPropertyAnimator, you should use a subclass of Animator (like ObjectAnimator) to be able to use KTX capabilities. for example:

ObjectAnimator.ofFloat(view, "translationY", view.height.toFloat()).apply {
    duration = 3000
    interpolator = AccelerateInterpolator()
    // Using KTX extension function:
    doOnEnd { /** Do whatever you want **/ }
    start()
}