Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to start Animation immediately after onCreate?

I am following http://developer.android.com/guide/topics/graphics/view-animation.html#frame-animation with minor changes. I have decided to make the animation loop and want it to start from the get-go.

My animation is at drawable/listening.xml:

<animation-list
xmlns:android="http://schemas.android.com/apk/res/android"
android:oneshot="false">
<item
    android:drawable="@drawable/l_01"
    android:duration="200" />
<item
    android:drawable="@drawable/l_02"
    android:duration="200" />
<item
    android:drawable="@drawable/l_03"
    android:duration="200" />
</animation-list>

and my init code:

 @Override public void onWindowFocusChanged(boolean hasFocus)  { 
      super.onWindowFocusChanged(hasFocus); 
      animImg = (ImageView)findViewById(R.id.listen_anim);
      animImg.setBackgroundResource(R.drawable.listening);
      anim = (AnimationDrawable) animImg.getBackground(); 
      anim.start();
 };

All I see is the first frame and no other images.

like image 779
hunterp Avatar asked Sep 02 '11 22:09

hunterp


People also ask

How to start Animation in android?

Navigate to the app > res > Right-Click on res >> New >> Directory >> Name your directory as “anim”. Inside this directory, we will create our animations. For creating a new anim right click on the anim directory >> Animation Resource file and give the name to your file.

What is Android before onCreate?

onCreate is the first method to be called from activity ... You can show ur loading screen be setting the proper view in your oncreate method..... check this: http://developer.android.com/reference/android/app/Activity.html. Follow this answer to receive notifications.


1 Answers

It's already written in the tutorial:

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.

So move your call to start in one of those two places, depending on your wish. Based on your comment, move your call to start inside onWindowsFocusChanged().

EDIT So this is "How to do it":

@Override
public void onWindowFocusChanged(boolean hasFocus) {
    if(hasFocus){
        textView.startAnimation(AnimationUtils.loadAnimation(MainActivity.this,
            android.R.anim.slide_in_left|android.R.anim.fade_in));
    }   
}

The points to pay attention to are:

  • do not forget to write the if/else case to check the focus
  • and delete the auto-generated "super.onWindowFocusChanged(hasFocus);"
like image 66
Kheldar Avatar answered Sep 20 '22 18:09

Kheldar