J'ai utilisé AnimationDrawable dans le développement d'un projet, mais après avoir appelé start, il ne s'est pas exécuté. J'étais perplexe. J'ai cherché sur Google. Je vais le consigner.

Ce AnimationDrawable.start ne peut pas être écrit directement dans onClick, onStart, onResume ; cela est invalide et l'animation ne peut pas être lancée. Il ne peut être écrit que, par exemple, dans des écouteurs d'événements.

Voici plusieurs façons de lancer AnimationDrawable.

Première : lancer AnimationDrawable dans un écouteur d'événements. L'exemple suivant illustre un événement qui se produit lorsqu'une arborescence de vues est sur le point d'être dessinée.

AnimationDrawable ad;
ImageView iv = (ImageView) findViewById(R.id.animation_view);
iv.setBackgroundResource(R.drawable.animation);
ad = (AnimationDrawable) iv.getBackground();
iv.getViewTreeObserver().addOnPreDrawListener(opdl);

OnPreDrawListener opdl=new OnPreDrawListener(){
       @Override
        public boolean onPreDraw() {
                   ad.start();
                   return true; //注意此行返回的值
       }
};

Deuxième façon de lancer l'animation : (l'animation s'exécutera automatiquement lorsque l'Activity démarre)

ImageView image = (ImageView) findViewById(R.id.animation_view);
image.setBackgroundResource(R.anim.oldsheep_wait);
        animationDrawable = (AnimationDrawable) image.getBackground();
        RunAnim runAnim=new RunAnim();
        runAnim.execute("");

class RunAnim extends AsyncTask<String, String, String>
{
        @Override
        protected String doInBackground(String... params)
        {
            if (!animationDrawable.isRunning())
            {
                animationDrawable.stop();
                animationDrawable.start();
            }
            return "";
        }
}

Troisième façon de lancer l'animation : (l'animation s'exécutera automatiquement lorsque l'Activity démarre)

ImageView image = (ImageView) findViewById(R.id.animation_view);
image.setBackgroundResource(R.anim.oldsheep_wait);
animationDrawable = (AnimationDrawable) image.getBackground();
image.post(new Runnable()
{
    @Override
    public void run()
    {
        animationDrawable.start();
    }
});

Quatrième méthode pour démarrer une animation : (l'animation s'exécutera automatiquement lorsque l'Activity démarre)

ImageView image = (ImageView) findViewById(R.id.animation_view);
image.setBackgroundResource(R.anim.oldsheep_wait);
animationDrawable = (AnimationDrawable) image.getBackground();

@Override
public void onWindowFocusChanged(boolean hasFocus)
{
    animationDrawable.start();
    super.onWindowFocusChanged(hasFocus);
}