プロジェクト開発でAnimationDrawableを使用したが、startを呼び出しても実行されず、困惑した。Googleで調べてみた。記録しておく。
このAnimationDrawable.startはonClick、onStart、onResume内に直接記述することはできず、無効であり、アニメーションを起動できない。例えばイベントリスナーなどの中にのみ記述できる。
以下にAnimationDrawableを実行するいくつかの方法がある。
最初の方法:イベントリスナー内でAnimationDrawableをstartする。以下の例は、ビューツリーが描画されようとするときにイベントが発生する場合の例である。
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; //注意此行返回的值
}
};
2つ目の方法でアニメーションを起動する:(Activity起動時に自動的にアニメーションが実行される)
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 "";
}
}
3つ目の方法でアニメーションを起動する:(Activity起動時に自動的にアニメーションが実行される)
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();
}
});
4つ目の方法でアニメーションを起動する:(Activity起動時に自動的にアニメーションが実行される)
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);
}