我需要停止一个运行翻译动画。Animation的.cancel()方法没有效果;不管怎样,动画会一直播放到最后。

如何取消正在运行的动画?


当前回答

在经历了所有的事情之后,没有任何效果。当我在视图中应用多个动画时。 下面是对我有用的代码。 要启动连续淡入和淡出的动画

val mAnimationSet = AnimatorSet()
private fun performFadeAnimation() {
    val fadeOut: ObjectAnimator = ObjectAnimator.ofFloat(clScanPage, "alpha", 1f, 0f)
    fadeOut.duration = 1000
    val fadeIn: ObjectAnimator = ObjectAnimator.ofFloat(clScanPage, "alpha", 0f, 1f)
    fadeIn.duration = 1000
    mAnimationSet.play(fadeIn).after(fadeOut)
    mAnimationSet.addListener(animationListener)
    mAnimationSet.start()
}

连续循环的动画监听器

 private val animationListener=object : AnimatorListenerAdapter() {
    override fun onAnimationEnd(animation: Animator?) {
        super.onAnimationEnd(animation)
        mAnimationSet.start()
    }
}

停止循环中的动画。我做了以下事情。

private fun stopAnimation() {
    mAnimationSet.removeAllListeners()
}

其他回答

为了停止动画,你可以设置这样的objectAnimator不做任何事情,例如:

首先,当手动翻转时,会出现从左到右的动画:

flipper.setInAnimation(leftIn);
flipper.setOutAnimation(rightOut);

当切换到自动翻转时,就没有动画了

flipper.setInAnimation(doNothing);
flipper.setOutAnimation(doNothing);

doNothing = ObjectAnimator.ofFloat(flipper, "x", 0f, 0f).setDuration(flipperSwipingDuration);

因为没有其他答案提到它,你可以很容易地使用ValueAnimator的cancel()停止动画。

ValueAnimator在制作动画方面非常强大。下面是一个使用ValueAnimator创建翻译动画的示例代码:

ValueAnimator valueAnimator = ValueAnimator.ofFloat(0f, 5f);

int mDuration = 5000; //in millis
valueAnimator.setDuration(mDuration);

valueAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {

   @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        // Update your view's x or y coordinate
    }
});

valueAnimator.start();

然后通过调用停止动画

valueAnimator.cancel()`

在你调用startAnimation()的视图上调用clearAnimation()。

如果你正在使用动画监听器,设置v.setAnimationListener(null)。对所有选项使用下面的代码。

v.getAnimation().cancel();
v.clearAnimation();
animation.setAnimationListener(null);

在经历了所有的事情之后,没有任何效果。当我在视图中应用多个动画时。 下面是对我有用的代码。 要启动连续淡入和淡出的动画

val mAnimationSet = AnimatorSet()
private fun performFadeAnimation() {
    val fadeOut: ObjectAnimator = ObjectAnimator.ofFloat(clScanPage, "alpha", 1f, 0f)
    fadeOut.duration = 1000
    val fadeIn: ObjectAnimator = ObjectAnimator.ofFloat(clScanPage, "alpha", 0f, 1f)
    fadeIn.duration = 1000
    mAnimationSet.play(fadeIn).after(fadeOut)
    mAnimationSet.addListener(animationListener)
    mAnimationSet.start()
}

连续循环的动画监听器

 private val animationListener=object : AnimatorListenerAdapter() {
    override fun onAnimationEnd(animation: Animator?) {
        super.onAnimationEnd(animation)
        mAnimationSet.start()
    }
}

停止循环中的动画。我做了以下事情。

private fun stopAnimation() {
    mAnimationSet.removeAllListeners()
}