如何在android中停止ObjectAnimator?

问题描述 投票:0回答:3

我正在使用对象动画师为我的按钮创建闪烁效果。一切正常。只是我无法停止动画。这是一个错误还是我错过了一些东西。我有以下方法。

   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();
}
android objectanimator
3个回答
4
投票

您正在创建

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

1
投票

请参阅源代码

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

0
投票

在 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
}
© www.soinside.com 2019 - 2024. All rights reserved.