Android:如何在AnimationDrawable中获取当前帧

4

我需要关于Android的帮助。 我正在尝试创建一个老虎机游戏。因此,我正在使用AnimationDrawable来控制三个轮子的动画。这是animwheel.xml文件:

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

我将animation-list放置在主布局中的3个不同视图(三个轮子)中,使用属性android:background。

android:background="@drawable/animwheel"

现在,用户可以通过点击三个不同的按钮来停止动画。问题是如何知道视图当前正在显示哪张图片?是否有getCurrentFrame()方法或类似的方法?

提前感谢您的帮助!


2
阅读了这里的AnimationDrawable(http://goo.gl/e7kFU)之后,我发现它们有一个名为mCurFrame的变量来跟踪当前动画帧。但不幸的是,它是私有的。如果将其设置为公共的,它将更加有用。 - anticafe
1个回答

15

我也遇到了同样的问题,尝试了每一个函数都没有成功,因为像'getCurrentFrame()'这样的函数返回一次十六进制值,在每次运行应用程序时都会发生变化。所以,我做了一些事情来解决我的问题,并希望能解决你的问题:

与其尝试获取帧的图像名称(如'fruits1'),你需要获取帧的位置;假设用户在'fruits2'帧停止动画,那么这个帧的编号是1,因为0是'fruits1'帧。你该怎么做呢?

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

当你停止动画时,你会执行类似于这样的操作:

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;
    }
}

所以,变量'frameNumber'将保护帧的编号,在您的情况下为0、1或2。 如果有很多帧,您可以创建一个函数,根据帧的编号返回名称(例如:'fruits1','fruits2' ...),并使用数组来实现。


是的,那是唯一的解决方案。不清楚为什么他们将那个数据设置为私有的。 - Shirane85

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接