Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to get current frame in AnimationDrawable

Tags:

android

frame

I need help with Android. I'm trying to create a slot machine game. So, I'm using the AnimationDrawable for the three wheels. Here is the animwheel.xml file:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/animWheel"
android:oneshot="false" >

<item
    android:drawable="@drawable/fruits1"
    android:duration="200"/>
<item
    android:drawable="@drawable/fruits2"
    android:duration="200"/>
<item
    android:drawable="@drawable/fruits3"
    android:duration="200"/>
</animation-list>

I putted the animation-list in 3 different views (the three whells) in the main layout using the attribute android:background

android:background="@drawable/animwheel"

Now, the user can stop the animations by clicking on three different buttons. The problem is how can I know which is the picture that the view is displaying currently? Is there any getCurrentFrame() method or something like that?

Thank you in advance!

like image 647
Daniele Vitali Avatar asked Dec 06 '22 16:12

Daniele Vitali


1 Answers

I have the same problem, tried every function, and don't have success because the functions like 'getCurrentFrame()' returns a hexadecimal value that changes every time you run your application, so, I did something that resolve my problem, and hope that resolves yours:

Instead of trying to get the name of image of the frame ('fruits1'), you have to get the position of the frame, supose that user stoped animation in frame 'fruits2', so, the number of the frame is 1, because 0 is the frame 'fruits1'. How will you do that?

// Create the animation
myImage.setBackgroundResource(R.anim.myanimation);
myAnimation = (AnimationDrawable) myImage.getBackground();

When you stops the animation you do something like this:

myAnimation.stop();

// The variable that will guard the frame number
int frameNumber;

// Get the frame of the animation
Drawable currentFrame, checkFrame;
currentFrame = myAnimation.getCurrent();

// Checks the position of the frame
for (int i = 0; i < myAnimation.getNumberOfFrames(); i++) {
    checkFrame = myAnimation.getFrame(i);
    if (checkFrame == currentFrame) {
        frameNumber = i;
        break;
    }
}

So, the variable 'frameNumber' will guard the number of the frame, in your case, 0, 1, or 2. If will have a lot of frames, you could do a function that return the name ('fruits1', 'fruits2' ...) based on the number of the frame, using an array.

like image 74
Fabricio Leite Avatar answered Dec 20 '22 15:12

Fabricio Leite