项目开发用到了AnimationDrawable,调用start后没有运行,很纳闷。google搜了下。记录一下。

      这个AnimationDrawable.start不能直接写在onClick,onStart,onResume里面,是无效的,无法启动动画,只能写在比如事件监听当中。


      以下有几种运行AnimationDrawable的方式。

第一种:在事件监听中start AnimationDrawable 下面一个例子举例 当一个视图树将要绘制时产生事件


[java] view plain copy
  1. AnimationDrawable ad;  

  2. ImageView iv = (ImageView) findViewById(R.id.animation_view);  

  3. iv.setBackgroundResource(R.drawable.animation);  

  4. ad = (AnimationDrawable) iv.getBackground();  

  5. iv.getViewTreeObserver().addOnPreDrawListener(opdl);  

  6. OnPreDrawListener opdl=new OnPreDrawListener(){  

  7. @Override

  8. publicboolean onPreDraw() {  

  9.                   ad.start();  

  10. returntrue; //注意此行返回的值

  11.       }  

  12. };  


第二种方式启动动画:(在Activity启动时会自动运行动画)



[java] view plain copy
  1. ImageView p_w_picpath = (ImageView) findViewById(R.id.animation_view);  

  2. p_w_picpath.setBackgroundResource(R.anim.oldsheep_wait);  

  3.        animationDrawable = (AnimationDrawable) p_w_picpath.getBackground();  

  4.        RunAnim runAnim=new RunAnim();  

  5.        runAnim.execute("");  

  6. class RunAnim extends AsyncTask<String, String, String>  

  7. {  

  8. @Override

  9. protected String doInBackground(String... params)  

  10.        {  

  11. if (!animationDrawable.isRunning())  

  12.            {  

  13.                animationDrawable.stop();  

  14.                animationDrawable.start();  

  15.            }  

  16. return"";  

  17.        }  

  18. }  


第三种方式启动动画:(在Activity启动时会自动运行动画)



[java] view plain copy
  1. ImageView p_w_picpath = (ImageView) findViewById(R.id.animation_view);  

  2. p_w_picpath.setBackgroundResource(R.anim.oldsheep_wait);  

  3.        animationDrawable = (AnimationDrawable) p_w_picpath.getBackground();  

  4. p_w_picpath.post(new Runnable()  

  5. {  

  6. @Override

  7. publicvoid run()  

  8.            {  

  9.                animationDrawable.start();  

  10.            }  

  11.        });  


第四种方式启动动画:(在Activity启动时会自动运行动画)



[java] view plain copy
  1. ImageView p_w_picpath = (ImageView) findViewById(R.id.animation_view);  

  2. p_w_picpath.setBackgroundResource(R.anim.oldsheep_wait);  

  3.        animationDrawable = (AnimationDrawable) p_w_picpath.getBackground();  

  4. @Override

  5. publicvoid onWindowFocusChanged(boolean hasFocus)  

  6.    {  

  7.        animationDrawable.start();  

  8. super.onWindowFocusChanged(hasFocus);  

  9.    }  




转自:http://blog.csdn.net/liuhanhan512/article/details/7666821