Android Kotlin - 设置动画结束/完成监听器

Android Kotlin - set animation end / finish listener

val anim = swipe.animate()
        .rotationBy((-30).toFloat())
        .setDuration(1000)
        .translationX((-swipe.left).toFloat())
        .setInterpolator(AccelerateDecelerateInterpolator())

anim.start()

我需要一个动画结束监听器,我试过:

anim.setAnimationListener(object : Animation.AnimationListener {
    override fun onAnimationStart(p0: Animation?) {

    }

    override fun onAnimationRepeat(p0: Animation?) {

    }

    override fun onAnimationEnd(p0: Animation?) {

    }
})

但是得到这个错误

Unresolved reference: setAnimationListener

如何正确执行此操作?

根本原因

ViewPropertyAnimatorclass中,没有名为setAnimationListener的方法。

解决方案 1

anim.withEndAction {
    // Your code logic goes here.
}

解决方案 2

anim.setListener(object : Animator.AnimatorListener {
    override fun onAnimationRepeat(animation: Animator?) {}
    override fun onAnimationCancel(animation: Animator?) {}
    override fun onAnimationStart(animation: Animator?) {}

    override fun onAnimationEnd(animation: Animator?) {
        // Your code logic goes here.
    }
})

注意:如果用户在动画过程中离开屏幕,记得取消动画。

swipe.animate().cancel()