androidanimationdrawable

Frame Animations only start one time


I have created a frame animations by the code below. I want every time I click at the button the animation will start but it only work at first time.

<RelativeLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <ImageView
        android:id="@+id/image"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/frame"
        />

    <Button
        android:layout_centerInParent="true"
        android:id="@+id/button"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Start Animation"
        />

</RelativeLayout>

frame.xml

<animation-list
    android:oneshot="true"
    xmlns:android="http://schemas.android.com/apk/res/android"
    >
    <item android:drawable="@drawable/ic_heart_0" android:duration="300" />
    <item android:drawable="@drawable/ic_heart_50" android:duration="300" />
    <item android:drawable="@drawable/ic_heart_75" android:duration="300" />
    <item android:drawable="@drawable/ic_heart_100" android:duration="300" />
    <item android:drawable="@drawable/ic_heart_0" android:duration="300" />
</animation-list>

Activity

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        findViewById(R.id.button).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                startAnimation();
            }
        });
    }

    public void startAnimation(){
         ImageView img = (ImageView) findViewById(R.id.image);
        ((AnimationDrawable) img.getBackground()).start();
    }
}

How can I make the animation can start whenever I click at the Button? Any help or suggestion would be great appreciated.


Solution

  • Here is one solution that I found. I try to stop animation if it is running before I start it again. I think animation not stop even it have gone through all frame

    if(((AnimationDrawable) imageView.getBackground()).isRunning()){
          ((AnimationDrawable) imageView.getBackground()).stop();
    }
    ((AnimationDrawable) imageView.getBackground()).start();