Ich habe AnimationDrawable in einer Projektentwicklung verwendet, aber nach dem Aufruf von start lief es nicht. Ich war verwirrt. Ich habe bei Google gesucht. Ich möchte es festhalten.
Dieses AnimationDrawable.start kann nicht direkt in onClick, onStart, onResume geschrieben werden; es ist ungültig und die Animation kann nicht gestartet werden. Es kann nur zum Beispiel in Event-Listenern geschrieben werden.
Nachfolgend sind mehrere Möglichkeiten zum Ausführen von AnimationDrawable aufgeführt.
Erstens: Starten Sie AnimationDrawable in einem Event-Listener. Das folgende Beispiel veranschaulicht ein Ereignis, das eintritt, wenn ein View-Baum kurz vor dem Zeichnen steht.
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; //注意此行返回的值
}
};
Zweite Möglichkeit, die Animation zu starten: (die Animation wird automatisch ausgeführt, wenn die Activity startet)
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 "";
}
}
Dritte Möglichkeit, die Animation zu starten: (die Animation wird automatisch ausgeführt, wenn die Activity startet)
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();
}
});
Vierte Möglichkeit, eine Animation zu starten: (die Animation wird automatisch ausgeführt, wenn die Activity startet)
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);
}