Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Starting an AnimationDrawable in Android

Where should I start an AnimationDrawable that needs to animate when the activity is shown?

The developer guide recommends using onWindowFocusChanged, but this isn't always called when the activity is part of a TabHost.

I quote:

It's important to note that the start() method called on the AnimationDrawable cannot be called during the onCreate() method of your Activity, because the AnimationDrawable is not yet fully attached to the window. If you want to play the animation immediately, without requiring interaction, then you might want to call it from the onWindowFocusChanged() method in your Activity, which will get called when Android brings your window into focus.

like image 507
hpique Avatar asked Jul 19 '10 18:07

hpique


2 Answers

I know this question is a little bit old, but this may be helpful to someone happening across this question like I did. One way that I start my AnimationDrawable's is by creating a new Runnable and using the post method from the ImageView.

You can do like:

ImageView spinner = (ImageView) findViewById(R.id.my_imageView);
spinner.setBackgroundResource(R.drawable.spinner);
spinner.post(new Runnable() {
    public void run() {
        AnimationDrawable anim = (AnimationDrawable) spinner.getBackground();
        anim.start();
    }
});
like image 87
Dave Avatar answered Nov 13 '22 16:11

Dave


The parallel thread approach seems to be the most popular one, but it does raise 2 major issues:

  • According to the docs, all UI related code should run on the main (a.k.a "GUI") thread. While calling .start() on an AnimationDrawable might not be considered a pure UI operation, I still feel that it should follow that rule.
  • You can never know exactly when will your animation start. I've seen code with "magic" delay length values that were supposed to fix that. You should know tht God kills a baby kitten every time a programmer takes that approach.

So, I suggest using the very aptly named runOnUiThread() method. Calling it in onResume() will assure you that your animation code will run on the main thread, that it would run after the window is attached, you'd know where exactly the message is about to be processed and no kittens need to lose their lives:

@Override
protected void onResume()
{
    super.onResume();
    runOnUiThread(new Runnable() 
    {
        @Override
        public void run() 
        {
            animation.start();
        }
    });
}
like image 28
Vaiden Avatar answered Nov 13 '22 16:11

Vaiden