android AnimationDrawable運行的幾種方式

項目開發用到了AnimationDrawable,調用start後沒有運行,很納悶。google搜了下。記錄一下。java

       這個AnimationDrawable.start不能直接寫在onClick,onStart,onResume裏面,是無效的,沒法啓動動畫,只能寫在好比事件監聽當中。ide

  

       如下有幾種運行AnimationDrawable的方式。post

第一種:在事件監聽中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.   
  7. OnPreDrawListener opdl=new OnPreDrawListener(){  
  8.        @Override  
  9.         public boolean onPreDraw() {  
  10.                    ad.start();  
  11.                    return true//注意此行返回的值  
  12.        }  
  13.   
  14. };  


第二種方式啓動動畫:(在Activity啓動時會自動運行動畫)google

[java] view plain copy
  1. ImageView image = (ImageView) findViewById(R.id.animation_view);  
  2. image.setBackgroundResource(R.anim.oldsheep_wait);  
  3.         animationDrawable = (AnimationDrawable) image.getBackground();  
  4.         RunAnim runAnim=new RunAnim();  
  5.         runAnim.execute("");  
  6.   
  7. class RunAnim extends AsyncTask<String, String, String>  
  8. {  
  9.         @Override  
  10.         protected String doInBackground(String... params)  
  11.         {  
  12.             if (!animationDrawable.isRunning())  
  13.             {  
  14.                 animationDrawable.stop();  
  15.                 animationDrawable.start();  
  16.             }  
  17.             return "";  
  18.         }  
  19. }  


第三種方式啓動動畫:(在Activity啓動時會自動運行動畫)spa

[java] view plain copy
  1. ImageView image = (ImageView) findViewById(R.id.animation_view);  
  2. image.setBackgroundResource(R.anim.oldsheep_wait);  
  3.         animationDrawable = (AnimationDrawable) image.getBackground();  
  4. image.post(new Runnable()  
  5. {  
  6.             @Override  
  7.             public void run()  
  8.             {  
  9.                 animationDrawable.start();  
  10.             }  
  11.         });  


第四種方式啓動動畫:(在Activity啓動時會自動運行動畫).net

[java] view plain copy
  1. ImageView image = (ImageView) findViewById(R.id.animation_view);  
  2. image.setBackgroundResource(R.anim.oldsheep_wait);  
  3.         animationDrawable = (AnimationDrawable) image.getBackground();  
  4.   
  5. @Override  
  6.     public void onWindowFocusChanged(boolean hasFocus)  
  7.     {  
  8.         animationDrawable.start();  
  9.         super.onWindowFocusChanged(hasFocus);  
  10.     }  
相關文章
相關標籤/搜索