Button states with Background as AnimationDrawable in Android

You’re doing incorrect cast — your background drawable is StateListDrawable, not AnimationDrawable. I’d rather do something like:

@Override
public void onWindowFocusChanged(boolean hasFocus) {
  super.onWindowFocusChanged(hasFocus);
  btn = (Button)findViewById(R.id.btnAnim);
  StateListDrawable background = (StateListDrawable) btn.getBackground();
  Drawable current = background.getCurrent();
  if (current instanceof AnimationDrawable) {
      btnAnimation = (AnimationDrawable) current;
      btnAnimation.start();
  }
}

Leave a Comment