我正在使用对象动画师为我的按钮创建闪烁效果。一切正常。只是我无法停止动画。这是一个错误还是我错过了一些东西。我有以下方法。
public void manageBlinkEffect(View view){
objectAnimator = ObjectAnimator.ofInt(view, "backgroundColor", Color.GRAY, Color.YELLOW);
objectAnimator.setDuration(1000);
objectAnimator.setEvaluator(new ArgbEvaluator());
objectAnimator.setRepeatMode(ValueAnimator.REVERSE);
objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
objectAnimator.start();
}
public void stopBlinkEffect(View view){
objectAnimator = ObjectAnimator.ofInt(view, "backgroundColor", Color.GRAY, Color.YELLOW);
objectAnimator.cancel();
}
您正在创建
object
的新 ObjectAnimator
来停止由不同 ObjectAnimator
启动的动画。
应该是这样的
ObjectAnimator objectAnimator;
public void manageBlinkEffect(View view){
objectAnimator = ObjectAnimator.ofInt(view, "backgroundColor", Color.GRAY, Color.YELLOW)
objectAnimator.setDuration(1000);
objectAnimator.setEvaluator(new ArgbEvaluator());
objectAnimator.setRepeatMode(ValueAnimator.REVERSE);
objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
objectAnimator.start();
}
public void stopBlinkEffect(View view){
objectAnimator.cancel();
}
请参阅源代码,
ObjectAnimator.ofInt(view, "backgroundColor", Color.GRAY, Color.YELLOW);
每次都会返回新对象。
你应该:
public void manageBlinkEffect(View view){
objectAnimator = ObjectAnimator.ofInt(view, "backgroundColor",
Color.GRAY, Color.YELLOW);
objectAnimator.setDuration(1000);
objectAnimator.setEvaluator(new ArgbEvaluator());
objectAnimator.setRepeatMode(ValueAnimator.REVERSE);
objectAnimator.setRepeatCount(ValueAnimator.INFINITE);
objectAnimator.start();
}
public void stopBlinkEffect(View view){
objectAnimator.cancel();
}
在 Kotlin 中只需调用
objectAnimator.cancel()
val objectAnimator = ObjectAnimator()
fun showSpinner(value: Boolean) {
if (value) {
objectAnimator.target = binding.imageView // has a spinner image inside of it
objectAnimator.setProperty(View.ROTATION)
objectAnimator.setFloatValues(0.0f, 360.0f)
objectAnimator.duration = 1200
objectAnimator.interpolator = LinearInterpolator()
objectAnimator.repeatMode = ObjectAnimator.RESTART
objectAnimator.repeatCount = ObjectAnimator.INFINITE
objectAnimator.start() // <- Starts the animation
return
}
objectAnimator.cancel() // <- Stops the animation
}