让Android AnimatorSet停止制作动画

我有以下AnimatorSet方法:

private AnimatorSet dialCenterThrob() {
    int bpm = workoutStream.getHeartRate();
    dialCenterImageView.clearAnimation();
    AnimatorSet finalSet = new AnimatorSet();

    ObjectAnimator pulseX = ObjectAnimator.ofFloat(dialCenterImageView, View.SCALE_X, 0.98f, 1.06f);
    ObjectAnimator pulseY = ObjectAnimator.ofFloat(dialCenterImageView, View.SCALE_Y, 0.98f, 1.06f);

    pulseX.setRepeatMode(ObjectAnimator.REVERSE);
    pulseX.setRepeatCount(ObjectAnimator.INFINITE);
    pulseY.setRepeatMode(ObjectAnimator.REVERSE);
    pulseY.setRepeatCount(ObjectAnimator.INFINITE);
    pulseX.setDuration(bpm);
    pulseY.setDuration(bpm);
    pulseX.setInterpolator(new AccelerateInterpolator());
    pulseY.setInterpolator(new AccelerateInterpolator());

    finalSet.playTogether(pulseX, pulseY);

    return finalSet;
}

这是在var上设置的,称为throbber,偶尔会通过以下方法更新:

private void updateThrobbing() {
    if (hasThrob()) {
        throbber = dialCenterThrob();
        throbber.start();
    } else {
        if (throbber != null && throbber.isRunning()) {
            stopThrobbing();
        }
    }
}

但我不能让它停止动画,这是目前尝试这样做的方法:

public void stopThrobbing() {
    List<Animator> throbbers = throbber.getChildAnimations();
    for(Animator animator : throbbers) {
        //accomplishes nothing
        ((ObjectAnimator)animator).setRepeatCount(0);
        ((ObjectAnimator)animator).setRepeatMode(0);
    }

    throbber.pause(); //nothing
    throbber.cancel(); //and again, nothing
    throbber.end();//shocking, I know, but really, nothing
    throbber = null;//you'd think this would definitely do it, but no
    //desparate attempt, in vein, of course
    dialCenterImageView.clearAnimation();
}

我不能让它停止动画.更新:我只是尝试将本地ref存储到单个对象动画师,然后调用setRepeatCount,mode,pause,end,取消每个,但仍然没有.

最佳答案

dialCenterImageView.clearAnimation();

这对ObjectAnimator创建的动画没有影响.您只能通过startAnimation()清除已在视图上启动的动画

findViewById(R.id.yourViewId).startAnimation(yourAnimation);
findViewById(R.id.yourViewId).clearAnimation();

any object animator, or animatorset with repeatCount set to Infinite will NOT stop, no matter what you do, short of leaving the view.

诚然!今天学到了这个艰难的道路.所以会增加我的两分钱.您需要存储ObjectAnimator实例的引用,然后在其上调用cancel().

旋转Android手机屏幕后动画仍在继续时我遇到了这种情况,在这种情况下,您的活动基本上是用新布局重新创建的.

所以这就是我所做的

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    ObjectAnimator buttonOneObjectAnimator = myOnClickListener.getButtonOneColorAnim();
    if(buttonOneObjectAnimator != null)
        buttonOneObjectAnimator.cancel();
}

你也可以在onPause()中做到这一点.

另一个需要注意的重点.如果你在ObjectAnimator实例上调用start()n次,则必须调用cancel()n次以使动画完全停止.

此外,如果您添加了AnimatorSet侦听器,请确保在调用cancel之前删除了侦听器.

yourAnimatorSet.removeAllListeners();
yourAnimatorSet.end();
yourAnimatorSet.cancel();

转载注明原文:让Android AnimatorSet停止制作动画 - 代码日志