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();
}
}
My answer is a bit late, I know, but I faced the same issue. I checked a lot of solutions, but found only one. I have tried to start the animation in onWindowFocusChanged(), start the animation in aseparate thread, but it doesn't help.
I solved this issue using setVisible (boolean visible, boolean restart)
So you can try this:
private Button ImgBtn;
private AnimationDrawable btnAnimation;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btn = (Button)findViewById(R.id.button1);
StateListDrawable background = (StateListDrawable) btn.getBackground();
btnAnimation = (AnimationDrawable) background.getCurrent();
btnAnimation.setVisible(true, true); // it works even in onCreate()
}
Hope this will help somebody :)