如何在 Android 中多次播放可绘制动画?

How to play animation drawable more than once in Android?

我有一个来自 png 的可绘制动画,android:oneshot="true" 因为我不希望动画持续播放,但只有在我激活它时才播放。问题是它只播放一次,当我尝试 myAnimation.play(); 它不会再次播放。

我试过 myAnimation.stop(); 并再次播放,但它使动画在动画结束前停止。

当我用 myAnimation.run(); 开始动画时,同样的事情发生了,虽然我不知道有什么区别。

//in onCreate() method
imageView = findViewById(R.id.imageView);
imageView.setBackgroundResource(R.drawable.animation_drawable);
myAnimation = (AnimationDrawable) imageView.getBackground();

//Triggers in somewhere else in a thread
myAnimation.start();
//animation_drawable.xml
<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/animation_drawable" android:oneshot="true">
    <item android:drawable="@drawable/kapali" android:duration="0"/>
    <item android:drawable="@drawable/acik" android:duration="500"/>
    <item android:drawable="@drawable/kapali" android:duration="0"/>
</animation-list>

在您的 animation_drawable.xml 中您有 android:oneshot="true",将其删除或更改为 false

尝试使用

myAnimation.setOneShot(false);

在 start() 方法之前。

当你想停止动画时使用

myAnimation.stop();

对于您的情况,停止动画后(或设置 oneshot=true),要重新启动动画,请使用

myAnimation.setVisible(/*visible=*/true,/*restart=*/true);

您可以查看此方法的文档here