如何停止ImageView上的无限动画,但让其完成当前周期?

5

我在我的应用程序中为ImageView应用了无限动画,以指示正在运行的后台线程。当线程完成时,我可以使用clearAnimation()停止动画,但它会将ImageView强制回到其起始位置,而我希望当前的动画周期能够完成(该动画周期旨在优雅地结束并回到起始位置)。有没有办法做到这一点?

4个回答

7

注册一个AnimationListener,并等待直到onAnimationRepeat()来清除它。我没有尝试过这个方法,但我认为它会起作用。


糟糕,那本来是完美的,但是onAnimationRepeat()没有被调用,而且这似乎是一个长期存在的bug:http://code.google.com/p/android/issues/detail?id=13397(onAnimationStart可以工作,如果我将动画的repeatCount设置为有限的数字,则onAnimationEnd也可以工作) - wirbly
1
@wirbly:嗯,你可以尝试通过执行单个动画,然后在onAnimationEnd()上重新启动动画来自己制作“无限”效果。不确定它是否会像无限变化那样平滑。如果这样做有效,你只需在想要消失的动画结束时不启动下一个动画即可。 - CommonsWare

7

只需调用setRepeatCount(0),然后监听onAnimationEnd。有关更多详细信息,请参见此处


只需将重复计数设置为零,对我来说就可以了。我没有监听onAnimationEnd,但似乎工作得很好。 - Henry
@Henry 我的用例有点复杂(一个在刷新时进行动画的刷新按钮),所以我需要使用onAnimationEnd来隐藏动画进度指示器,并将其替换为按钮。此外,还需要一些解决方法来使过渡完美顺畅。有关详细信息,请参见我链接的答案。只有在您需要知道动画实际停止时才需要使用onAnimationEnd,因为当您调用setRepeatCount(0)时它不会立即停止,而是先完成当前周期(这就是整个重点)。 - user1431317

2

您可以在动画监听器的onAnimationEnd()方法中设置所需的动画位置。然后,视图将显示在您在那里设置的坐标处,而不是返回到初始位置。

animation = new TranslateAnimation(0, -length, 0, 0); //setup here your translation parameters
animation.setInterpolator(new LinearInterpolator());
animation.setDuration(10);
animation.setAnimationListener(new Animation.AnimationListener() {
    public void onAnimationStart(Animation animation) {
        animationRunning = true;
    }
    public void onAnimationRepeat(Animation animation) {
    }
    public void onAnimationEnd(Animation animation) {
        animationRunning = false;
        // setAnimationPositionAfterPositionChange();
        LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) runningText.getLayoutParams();
        params.leftMargin  = currentPosition; //Calculate you current position here
        runningText.setLayoutParams(params);
    }
});
runningText.setAnimation(animation);

0

如果你正在使用animate(),你可以使用setListener(null)来停止动画,这对我很有效。

    image.animate()
            .translationXBy(-width* 0.5f)
            .setDuration(300)
            .setStartDelay(6000)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    image.animate().rotationBy(90).setDuration(1000).setStartDelay(1).setListener(null);
                }
            });

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接