首页 > 解决方案 > 具有递归函数的反向动画

问题描述

在android上反转动画方向的最佳做法是什么?另外,我在分析器上跟踪 ram 使用情况,结果是正常的。我确实喜欢下面的代码:

 var flagHeight: Int = 100
    private fun startAnimation() {
        val animation = tv_hello_world.animate().apply {
            translationYBy(flagHeight.toFloat())
            setListener(object : Animator.AnimatorListener {
                override fun onAnimationStart(p0: Animator?) {
                    // do nothing
                }

                override fun onAnimationEnd(p0: Animator?) {
                    flagHeight = flagHeight.not()
                    startAnimation()
                }

                override fun onAnimationCancel(p0: Animator?) {
                    // do nothing
                }

                override fun onAnimationRepeat(p0: Animator?) {
                    // do nothing
                }
            })
            duration = 1000
        }
        animation.start()
    }

    fun Int.not() = run { if (this > 0) -this else (this * -1) }



   

标签: androidanimationrecursionreverse

解决方案


正确的方法是使用ValueAnimatorinstead on,PropertyAnimator因为您可以更好地控制它。试试这种方式:

val animator = ValueAnimator.ofFloat(0f, 100f).apply {
        duration = 1000
        repeatCount = ValueAnimator.INFINITE
        repeatMode = ValueAnimator.REVERSE
        addUpdateListener {
            tv_hello_world.translationY = it.animatedValue as Float
        }
    }
    animator.start()

推荐阅读