Matt Becker
Matt Becker

Reputation: 2368

animation-list not animating initially

I have a checkbox that should look like a green light when checked and a red blinking light when unchecked. To do this I created a selector called connected_selector.xml.

<?xml version="1.0" encoding="utf-8"?>
<selector
  xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_checked="true" android:drawable="@drawable/green_button" />
    <item android:state_checked="false" android:drawable="@drawable/red_button_blinking" />
    <item android:drawable="@drawable/red_button_blinking" />
</selector>

The green_button is simply a png and the red_button_blinking is an animation-list of pngs.

<?xml version="1.0" encoding="utf-8"?>
<animation-list
  xmlns:android="http://schemas.android.com/apk/res/android" android:oneshot="false">
    <item android:drawable="@drawable/red_button" android:duration="500" />
    <item android:drawable="@drawable/red_button_lit" android:duration="500" />
</animation-list>

The checkbox's background is set to @drawable/connected_selector. If the checkbox is initially unchecked, it doesn't blink, it just shows the @drawable/red_button. However if I check the box and then uncheck it, the checkbox will animate correctly.

How can I make the animation start initially since the checkbox will be initially unchecked? I guess I could try to start the animation manually in code, but I don't think that should be necessary.

Upvotes: 2

Views: 1004

Answers (1)

stfn
stfn

Reputation: 1140

Okay, I found an ugly, dirty hack to get around this. Note that I don't have the slightest clue why this happens, just a way around this. It is probably not even a generic way since different devices will have different loading times.

I execute the following workaround in onPostResume() to minimize the necessary delay time.

if(onOffStatus) {
    // SLEEP 0.5 SECONDS HERE ...
    new Handler().postDelayed(new Runnable() { 
        public void run() {
            switcher.setBackgroundResource(R.drawable.button_state_anim);

            // Get the background, which has been compiled to an AnimationDrawable object.
            AnimationDrawable frameAnimation = (AnimationDrawable) switcher.getBackground();
            // Start the animation (looped playback by default).
            frameAnimation.start();
        } 
    }, 500); // Actual required time will probably be dependent on device performance
}

It ain't pretty but I'm going with this until I find something better. Let me know if I overlooked something here.

Upvotes: 3

Related Questions