gpt4 book ai didi

android - 如何重复 Android 动画

转载 作者:行者123 更新时间:2023-12-04 23:50:21 27 4
gpt4 key购买 nike

我试图让两个 View 移动到屏幕中间并再次反弹 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 动画,但我没有嫁给它。如果有另一个动画可以实现这一点,我会完全愿意改变。

最佳答案

您可以运行多个 SpringAnimation同上View通过反复调用animateToFinalPosition(translation)带有一系列翻译值。
例如:

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

关于android - 如何重复 Android 动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71310134/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com