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

Edu*_*ruh 2 android android-animation kotlin

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

anim.start()
Run Code Online (Sandbox Code Playgroud)

我需要一个动画完成侦听器,我尝试过:

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

    }

    override fun onAnimationRepeat(p0: Animation?) {

    }

    override fun onAnimationEnd(p0: Animation?) {

    }
})
Run Code Online (Sandbox Code Playgroud)

但得到这个错误

未解决的参考:setAnimationListener

如何正确地做到这一点?

Nhấ*_*ang 5

根本原因

ViewPropertyAnimator类中,没有名为 的方法setAnimationListener

解决方案1

anim.withEndAction {
    // Your code logic goes here.
}
Run Code Online (Sandbox Code Playgroud)

解决方案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.
    }
})
Run Code Online (Sandbox Code Playgroud)

注意:如果用户在动画播放时离开屏幕,请记住取消动画。

swipe.animate().cancel()
Run Code Online (Sandbox Code Playgroud)