項目開發用到了AnimationDrawable,調用start後沒有運行,很納悶。google搜了下。記錄一下。java
這個AnimationDrawable.start不能直接寫在onClick,onStart,onResume裏面,是無效的,沒法啓動動畫,只能寫在好比事件監聽當中。ide
如下有幾種運行AnimationDrawable的方式。post
第一種:在事件監聽中start AnimationDrawable 下面一個例子舉例 當一個視圖樹將要繪製時產生事件動畫
- 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;
- }
-
- };
第二種方式啓動動畫:(在Activity啓動時會自動運行動畫)google
- 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 "";
- }
- }
第三種方式啓動動畫:(在Activity啓動時會自動運行動畫)spa
- 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();
- }
- });
第四種方式啓動動畫:(在Activity啓動時會自動運行動畫).net
- 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);
- }