是否有可能在Android动画中获取当前帧号

时间:2016-10-27 16:16:18

标签: android android-animation

我正在开发一个应用程序,其中我想在几帧加载之后更改文本视图,如第一个文本视图将是默认的,然后在4帧加载文本视图后应该再次更改然后在9帧加载文本视图后应该更改。我怎么能这样做?

1 个答案:

答案 0 :(得分:1)

您可以通过覆盖selectDrawable(int idx)类的AnimationDrawable方法来执行此操作。为此你应该创建自定义类,扩展AnimationDrawable声明接口OnFrameChangeListener并在帧改变时引发onFrameChanged()方法:

public class ExtendedAnimationDrawable扩展了AnimationDrawable {

public interface OnFrameChangeListener {
    void onFrameChanged(int numOfFrame);
}

private OnFrameChangeListener mFrameChangeListener;

public ExtendedAnimationDrawable(AnimationDrawable aniDrawable) {
    for (int i = 0; i < aniDrawable.getNumberOfFrames(); i++) {
        this.addFrame(aniDrawable.getFrame(i), aniDrawable.getDuration(i));
    }
}

public void setFrameChangeListener(OnFrameChangeListener frameChangeListener) {
    this.mFrameChangeListener = frameChangeListener;
}

@Override
public boolean selectDrawable(int idx) {
    boolean result = super.selectDrawable(idx);

    if (mFrameChangeListener != null) {
        mFrameChangeListener.onFrameChanged(idx);
    }

    return result;
}

}

比你可以这样使用它:

View v ;

...

v.setBackgroundResource(R.drawable.animation_list);
ExtendedAnimationDrawable extendedAnimation = new ExtendedAnimationDrawable(
        (AnimationDrawable) ContextCompat.getDrawable(context, R.drawable.animation_list));
extendedAnimation.setFrameChangeListener(new ExtendedAnimationDrawable.OnFrameChangeListener() {
    @Override
    public void onFrameChanged(int numOfFrame) {
        // do your magic here
        // for example
        if (numOfFrame == 4) {
           // change TextView #1
        }
        if (numOfFrame == 4 + 9) {
           // change TextView #2
        }
    }
});

int sdk = android.os.Build.VERSION.SDK_INT;
if(sdk < android.os.Build.VERSION_CODES.JELLY_BEAN) {
    v.setBackgroundDrawable(extendedAnimation);
} else {
    v.setBackground(extendedAnimation);
}

extendedAnimation.start();