我正在开发一个应用程序,在该应用程序中,我希望在几帧加载后更改文本视图,如第一个文本视图将是默认设置,然后在4帧加载后文本视图应更改,然后在9帧加载后应再次更改文本视图。我怎样才能做到这一点?

最佳答案

您可以通过重写selectDrawable(int idx)类的AnimationDrawable方法来实现。为此,您应该创建扩展AnimationDrawable的自定义类,以声明接口OnFrameChangeListener并在更改框架时引发onFrameChanged()方法,如下所示:

公共类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();

08-05 00:46