So I want my animation to start as soon as the activity is created, but for some reason no matter what I try will get it to start. I can get it to start by having a click ev
My solution for playing animations while they are visible. It let you declare (in xml layout) and forget.
class AnimatedImageView extends ImageView {
// required constructors omitted for clarity
private void updateAnimationsState() {
boolean running = getVisibility() == View.VISIBLE && hasWindowFocus();
updateAnimationState(getDrawable(), running);
updateAnimationState(getBackground(), running);
}
private void updateAnimationState(Drawable drawable, boolean running) {
if(drawable instanceof AnimationDrawable) {
AnimationDrawable animationDrawable = (AnimationDrawable) drawable;
if(running) {
animationDrawable.start();
} else {
animationDrawable.stop();
}
}
}
@Override
protected void onVisibilityChanged(View changedView, int visibility) {
super.onVisibilityChanged(changedView, visibility);
updateAnimationsState();
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
updateAnimationsState();
}
}
If you setup drawable from code, then you should override appropriate set*() methods and call updateAnimationsState() from there.