如何在动画循环结束时停止动画?

9
我有一个ImageView用作加载动画的旋转效果。当数据加载完毕后,我尝试停止动画,但是它并没有到达最后的状态就停了下来,反而在中途停住了,然后图像会突然回到原始状态,看起来很不好看。
以下是我尝试过的方法:
选项1:
ImageView iv = (ImageView) findViewById(R.id.refreshImage);
if (iv != null) {
    iv.clearAnimation();
}

方案二:

ImageView iv = (ImageView) findViewById(R.id.refreshImage);
if (iv != null && iv.getAnimation() != null) {
    iv.getAnimation().cancel();
}

选项3:

ImageView iv = (ImageView) findViewById(R.id.refreshImage);
if (iv != null && iv.getAnimation() != null) {
    iv.getAnimation().setAnimationListener(new AnimationListener() {

        @Override
        public void onAnimationStart(Animation animation) {

        }

        @Override
        public void onAnimationRepeat(Animation animation) {
            animation.cancel();

        }

        @Override
        public void onAnimationEnd(Animation animation) {

        }
    });
}

三种情况的最终结果是相同的。我如何旋转图像并使其回到起始位置?
编辑:
一些进一步的信息:我的旋转动画:
<?xml version="1.0" encoding="utf-8"?>
<rotate xmlns:android="http://schemas.android.com/apk/res/android"
android:duration="1000"
android:fromDegrees="0"
android:interpolator="@android:anim/linear_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="360" />

我如何启动动画:

ImageView iv = (ImageView) findViewById(R.id.refreshImage);
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate);
rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);
3个回答

17
在启动动画之前将其重复次数设置为无限,然后当动作结束时,将动画的重复次数设置为0。这样动画将完成当前循环,并停止而不会出现您想要避免的跳跃。
//How you start
Animation rotation = AnimationUtils.loadAnimation(this, R.anim.rotate);
          rotation.setRepeatCount(Animation.INFINITE);
iv.startAnimation(rotation);

//You do your stuff while it spins
...

//You tell it not to repeat again
rotation.setRepeatCount(0);

很重要的是,您首先将其设置为Animation.INFINITE(或-1,因为它们相同),然后再将其设置为0。如果您将其设置为例如1000,则根据我的测试,它不会停止,原因未知。


我的一些动画仍然有点卡顿,但对于大多数情况下都能正常工作,谢谢! - Catherine
2
@Catherine 对于同时发生多个事情的动画集,它可能看起来有些跳跃,但对于简单的动画来说,这是正确的方法。我还没有测试过。 - Juan Cortés
谢谢你的妙招。如果 Android 提供了一个名为 stopAfterCycleCompletion() 或类似的 API 就更好了。 - rpattabi
1
这个方法可能在5年前可行,但现在动画会突然停止。 - Ves
将其作为社区Wiki,因为这是一个比较受欢迎的答案,以防其他人想要更新它。目前我有点不了解情况。 - Juan Cortés

1

感谢您提供这个代码片段,它可能会提供一些有限的即时帮助。一个适当的解释可以大大提高它的长期价值,因为它展示了为什么这是一个好的解决方案,并使其对未来读者的其他类似问题更有用。请[编辑]您的答案以添加一些解释,包括您所做出的假设。 - Dwhitz

-2

使用iv.clearAnimation();停止动画


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