19

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.

3
  • If you followed it to the letter, than why is your start() call inside the init and not inside onTouchEvent? Sep 2, 2011 at 22:40
  • You have put that init code exactly as advised 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."
    – Kheldar
    Sep 2, 2011 at 22:41
  • Ok, but I want the animation to start on load not on touch, how to accomplish?
    – hunterp
    Sep 2, 2011 at 22:44

7 Answers 7

51

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);"
11
  • 1
    This fails: @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(); };
    – hunterp
    Sep 2, 2011 at 22:50
  • Also, be nice. If I take the time to edit your question and tags, it's in the interest of others who might make the same mistake. How does your override "fail" exactly?
    – Kheldar
    Sep 2, 2011 at 22:54
  • Based on the tutorial, again, I'd advise you to put the declarations inside onCreate and only the call to start inside onWindowsFocusChanged
    – Kheldar
    Sep 2, 2011 at 23:07
  • Well, if it suits you, you've solved your issue. Launching a special thread just for setting up the animation seems a bit over the top to me, but you might have some good reason to do so that you're withholding.
    – Kheldar
    Sep 2, 2011 at 23:13
  • 3
    How about fragment? There's no onWindowFocusChanged() in a fragment.
    – Song
    Jan 16, 2016 at 1:44
9

Have a flag set in onAttachedToWindow() and then in onWindowFocusChanged() check it and start the animation.

@Override
void onWindowFocusChanged(boolean hasFocus) {
    if (hasFocus & mbFlag) {
        // start animation.
    }
}

Update

Simply extend the ImageView class and override onFocusChange method. Then in your activity set the focus to it by calling animImg.requestFocus(). The animation should start when it gets focused. Make sure your imageview is focusable.

If this does not work, you may want to override the onAttachedToWindow() method also. Set a flag in there and check before starting the animation.

@Override
void onFocusChange(boolean hasFocus) {
    if (hasFocus) {
        // start animation.
    }
}
1
  • which view's onAttachedToWindow do you recommend?
    – hunterp
    Sep 4, 2011 at 20:26
8

You can use the post method of any View on the activity. It should probably look like this:

View anyView = findViewById(R.id.anyView);
anyView.post(new Runnable()
{
    @Override
    public void run()
    {
        // Your code goes here
    }
});
0

You need to give time to UI manager create appropiate resources BEFORE starting animation. Correct pattern is

a) Create animation object in onCreate.
b) Start animation object elsewhere.

Don't create and start in same method.

2
  • Yes ruhalde, see our discussion and his solution where we have pointed this out.
    – Kheldar
    Sep 2, 2011 at 23:14
  • Ok, but nobody explains why you have to do it that way Is all about single threading model of Android, while your code is executing UI manager is not working, that's why you should create in OnCreate then exit (UI manager create proper resources) and then you do Start() in your code and exit again (UI manager stat animation).
    – ruhalde
    Sep 2, 2011 at 23:23
0

As this question was asked some long time ago, I have encounter same problem in 2019 with usage of transitions-Everywhere or AndroidX Transitions. And the only solution for me was to use @Muzikant answer. Simply call in your onCreate()

rootViewOfYourLayout.post {
            TransitionManager.beginDelayedTransition(rootViewOfYourLayout)
            someViewId.visibility = View.VISIBLE
        }

And it works perfectly, for example in my case for Splash screen.

Update
As after some testing, it appears this solution has minor issue. Animation is started and you block the phone or move app to background, and in result when app again in foreground it's just frozen as no TransitionListener callbacks received, so in my case onTransitionEnd() wasn't called where was located logic to navigate user to next screen.

For now this works for me without problems :

  override fun onWindowFocusChanged(hasFocus: Boolean) {
   if(hasFocus && isAnimationStarted.not()){
   rootViewOfYourLayout.post {
          TransitionManager.beginDelayedTransition(rootViewOfYourLayout)
          someViewId.visibility = View.VISIBLE
            }
  }
}
-1
animation = AnimationUtils.loadAnimation(this, R.anim.push_left_out);

yourobject.startanimation(animation);

This may help

-18

Run this in onResume():

class AnimTask extends AsyncTask<String, String,String> {
            Activity act;
            AnimTask(Activity act) {
                this.act = act;
            }

            @Override
            protected String doInBackground(String... params) {
                act.runOnUiThread(new Runnable() {
                    public void run(){
                        animImg = (ImageView)findViewById(R.id.listen_anim);
                        animImg.setBackgroundResource(R.drawable.listening);
                        anim = (AnimationDrawable) animImg.getBackground();
                        anim.start();
                    }
                });
                return null;
            }
        }
6
  • Whoever -1 this better have an explanation
    – hunterp
    Sep 2, 2011 at 23:13
  • 4
    I don't know who put it that negative but this code has serious problems, you NEVER update UI objecst outside UI thread. Check that doInBackground(), is executed OUTSIDE UI thread.
    – ruhalde
    Sep 2, 2011 at 23:28
  • The problem when you attempt to run the thread directly inside the activity is that it complains that it is not run on the UI thread. If you simply try to start the anim in onResume, nothing happens, I suppose slightly cleaner is to create a Thread in onResume and call Activity.this.runOnUiThread() , and so I don't believe you have a point sir.
    – hunterp
    Sep 3, 2011 at 2:39
  • 3
    The point is that this code IS WRONG and you don't properly read android documentation. Stackoverflow is not a contest on who knows better what, this site is all about helping others, at least that's the way I'm using it and I have learned many things in here. So next time have more consideration with people that waste his/her own valuable time to help you.
    – ruhalde
    Sep 3, 2011 at 14:40
  • 3
    It works but it's a hacky solution. You're creating a race condition by hoping that the activity has finished setting up before the background thread runs. It may run on devices, but there is no guarantee that something won't change in future versions of android and the race condition will cause it to start failing.
    – Gabriel
    Jan 17, 2014 at 7:09

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.