Reputation: 33
I created a game in AndroidStudio, where you can move right and left through the buttons. Now I would like to add an animation. I have this image:
image
How do I change the animation when I click the left button and then stop it when no touch the button?
Is there a guide? Thanks for all.
Upvotes: 1
Views: 5239
Reputation: 330
First of all you have to create a xml and place the images. You have 6 frames in the sprite, you have to cut it making 6 images. Create a xml (e.g. run_animation.xml) and reference the images in there. For example like this:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" >
<item android:drawable="@drawable/run_0001" android:duration="50"/>
<item android:drawable="@drawable/run_0002" android:duration="50"/>
<item android:drawable="@drawable/run_0003" android:duration="50"/>
<item android:drawable="@drawable/run_0004" android:duration="50"/>
<item android:drawable="@drawable/run_0005" android:duration="50"/>
<item android:drawable="@drawable/run_0006" android:duration="50"/>
</animation-list>
If you don't want to loop the animation, you can use this in the xml: android:oneshot="true"
For example:
<animation-list xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="true">
Java:
runAnimation.setImageResource(R.drawable.run_animation);
AnimationDrawable idleAnimation = (AnimationDrawable)runAnimation.getDrawable();
idleAnimation.start();
In order to run the animation using a button, place the Java code above in the button click listener. For example:
btnRight.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// run animation
runAnimation.setImageResource(R.drawable.run_animation);
AnimationDrawable idleAnimation = (AnimationDrawable)runAnimation.getDrawable();
idleAnimation.start();
}
});
Upvotes: 4