我创建了一个非常简单的平移动画,第一次按下该按钮时,图像视图将向左移动,第二次图像视图将向右移动。距离是完全相同的。
但是第二次图像移动得更多,实际上并没有回到其原始位置。为了更准确,第二次图像移动距离是两倍。为什么?
private var direction = 1
fun move() {
val animatorX = ObjectAnimator.ofFloat(draggableImage1, "translationX", direction*(-100f))
val animatorY = ObjectAnimator.ofFloat(draggableImage1, "translationY", 0f)
animatorX.duration = (500)
animatorY.duration = (500)
val animationSet = AnimatorSet()
animationSet.playTogether(animatorX, animatorY)
animationSet.start()
if (direction == 1) {direction = -1} else {direction = 1}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
button.setOnClickListener{move()}
}
答案 0 :(得分:1)
您可以将以下代码用于动画,请尝试使用此更新的答案。
val animatorX: ObjectAnimator?
if (direction == 1) {
direction = -1
animatorX = ObjectAnimator.ofFloat(star, "translationX", -100f)
} else {
direction = 1
animatorX = ObjectAnimator.ofFloat(star, "translationX", 200f)
}
animatorX.duration = 500
animatorX.start()
答案 1 :(得分:1)
图像第二次到达距离两倍
因为在第一个动画之后,其x位置为(初始x-100),而第二次您将x设置为100。所以第二次它从-100到100,并且是第一次的两倍
要向右移动,请将translationX设置为0
private var direction = 1
fun move() {
var distance = -100f
if (direction == -1){
distance = 0f
}
val animatorX = ObjectAnimator.ofFloat(draggableImage1, "translationX", distance)
val animatorY = ObjectAnimator.ofFloat(draggableImage1, "translationY", 0f)
animatorX.duration = (500)
animatorY.duration = (500)
val animationSet = AnimatorSet()
animationSet.playTogether(animatorX, animatorY)
animationSet.start()
if (direction == 1) {direction = -1} else {direction = 1}
}
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main2)
button.setOnClickListener{move()}
}
答案 2 :(得分:0)
我确实希望有一种重置动画师的方法,但是如果没有,我确实找到了解决方法。您应该获取初始坐标,然后使用它来计算翻译:
val animatorX = ObjectAnimator.ofFloat(draggableImage1, "translationX", (draggableImage1.x - initalLeft) -(direction*100f))