javaandroidandroid-drawableanimationdrawable

How to play animation drawable more than once in Android?


I have one drawable animation from png, and android:oneshot="true" because I don't want the animation play constantly, but only when I activate it. Problem is it plays only once and when I try myAnimation.play(); it doesn't play again.

I've tried to myAnimation.stop(); and play again but it makes the animation stop before animation ends.

Same thing happens when I start the animation with myAnimation.run();, though I don't know the difference.

//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>


Solution

  • In your animation_drawable.xml you have android:oneshot="true", remove it OR change it to false.

    Try using

    myAnimation.setOneShot(false);
    

    before the start() method.

    And when you want to stop the animation use

    myAnimation.stop();
    

    For your case, after stopping the animation(OR set oneshot=true), to restart the animation, use

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

    You can check the documentation for this method here.