如何重复执行 Android 动画

4
我正在尝试让两个视图在屏幕中间移动并反弹 x 次。以下代码可以实现,但只运行一次。 `val view = findViewById(R.id.imageView2)`
    val animation = SpringAnimation(view, DynamicAnimation.TRANSLATION_Y, 0f)

    val view2 = findViewById<View>(R.id.imageView3)
    val animation2 = SpringAnimation(view2, DynamicAnimation.TRANSLATION_Y, 0f)

    findViewById<View>(R.id.imageView2).also { img ->
        SpringAnimation(img, DynamicAnimation.TRANSLATION_Y).apply {

            animation.getSpring().setDampingRatio(SpringForce.DAMPING_RATIO_HIGH_BOUNCY)

          
            animation.spring.stiffness = SpringForce.STIFFNESS_VERY_LOW

                animation.animateToFinalPosition(50f)
            

        }
    }
    findViewById<View>(R.id.imageView3).also { img ->
        SpringAnimation(img, DynamicAnimation.TRANSLATION_Y).apply {
            
            animation2.getSpring().setDampingRatio(SpringForce.DAMPING_RATIO_HIGH_BOUNCY)

            
            animation2.spring.stiffness = SpringForce.STIFFNESS_VERY_LOW
           
            animation2.animateToFinalPosition(-100f)
            

        }
    }`

那么我该如何让它运行x次呢? 显然这是Spring Animation,但我不一定非用它不可。如果有其他动画可以实现同样的效果,我完全可以考虑更换。


你的意思是你想让弹跳发生x次,还是想要触发整个动画超过一次? - Bö macht Blau
设置插值器? - Darkman
我是指触发整个动画不止一次。 - JettTexas
2个回答

0

您可以通过反复调用animateToFinalPosition(translation)并使用一系列translation值,在同一个View上运行多个SpringAnimation

例如:

startSpringAnimations(findViewById<View>(R.id.imageView1), 300f, 6)
startSpringAnimations(findViewById<View>(R.id.imageView2), -600f, 6)

使用一个函数
/**
 * [view] will be moved using [times] SpringAnimations over a distance of abs([totalTranslation])
 * If [totalTranslation] is negative, direction will be up, else down
 */
private fun startSpringAnimations(view: View, totalTranslation: Float, times: Int ) {
    if(times <= 0){
        return
    }

    val translation = totalTranslation/ times.toFloat()

    SpringAnimation(view, DynamicAnimation.TRANSLATION_Y, 0f).apply{
        spring.dampingRatio = SpringForce.DAMPING_RATIO_HIGH_BOUNCY
        spring.stiffness = SpringForce.STIFFNESS_VERY_LOW

        addEndListener(object: DynamicAnimation.OnAnimationEndListener{
            private var count = 1
            override fun onAnimationEnd(animation1: DynamicAnimation<*>?, canceled: Boolean, value: Float, velocity: Float) {
                Log.d("SpringAnimation", "onAnimationEnd: animation $animation1 canceled $canceled value $value velocity $velocity count $count")
                if (canceled) return

                count++
                if(count <= times){
                    animateToFinalPosition(translation * count)
                }
            }
        })
        animateToFinalPosition(translation)
    }
}

在我的系统上,这会导致动画从其起始位置开始移动,因此很快它们就会跑出屏幕。 - JettTexas
@JettTexas - 我认为应该根据设备的布局和屏幕尺寸选择翻译的值。重要的是,在重新启动动画之前,必须更改“最终位置”。 - Bö macht Blau

0

在动画文件夹中设置android:repeatCount="infinite"


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接