android之AnimationDrawable

來源:互聯網
上載者:User

AnimationDrawable是Android實現動畫的一種簡單的形式,可以用來實現幀動畫。

1.在res/drawable下定義friend.xml檔案:

<?xml version="1.0" encoding="utf-8"?><animation-list android:oneshot="false"xmlns:android="http://schemas.android.com/apk/res/android"><item android:duration="400" android:drawable="@drawable/friend_light" /><item android:duration="400" android:drawable="@drawable/friend" /></animation-list> 

其中,每一個item是一幀,android:duration="400"表示每幀持續400ms,android:drawable是每幀要顯示的圖片。

2.在java代碼中載入和執行動畫:

①載入動畫

Button friend = (Button)findViewById(R.id.friend_btn);friend.setBackgroundResource(R.drawable.friend_anim);AnimationDrawable friend_anim= (AnimationDrawable) friend.getBackground();

②執行動畫

friend_anim.start();

③停止動畫

friend_anim.stop();

3. 注意:

預設情況下,在OnCreate()中執行animation.start();是無效的,因為在OnCreate()中AnimationDrawable還沒有完全的與ImageView綁定,在OnCreate()中啟動動畫,就只能看到第一張圖片。

解決辦法:

①調用View的getViewTreeObserver().addOnPreDrawListener()

friend.getViewTreeObserver().addOnPreDrawListener(new OnPreDrawListener(){@Overridepublic boolean onPreDraw() {// TODO Auto-generated method stubfriend_anim.start();return true;}});

②使用Handler

public void onCreate(Bundle savedInstanceState) {    super.onCreate(savedInstanceState);    setContentView(R.layout.main);    friend = (Button)findViewById(R.id.friend_btn);    handler.postDelayed(new Runnable() {        public void run() {        friend.setBackgroundResource(R.drawable.friend_anim);        friend_anim = (AnimationDrawable) friend.getBackground();        friend_anim.start();        }    }, 50);} 

相關文章

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.