Aakash MEHTA Aakash MEHTA - 1 month ago 15
Android Question

is it possible to get current frame number in android animation

I am developing an application in which i want to change the text-view after few frames load like first text-view will be default then after 4 frames load text view should change then again after 9 frames load text-view should change. how can i do this?

Answer

You can do this by overriding selectDrawable(int idx) method of AnimationDrawable class. For that You should create custom class which extends AnimationDrawable declares interface OnFrameChangeListener and raises an onFrameChanged() method when frame changed like this:

public class ExtendedAnimationDrawable extends 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;
}

}

Than You can use it like this:

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();