【Android介面實現】Drawable Animation 使用介紹,androiddrawable

來源:互聯網
上載者:User

【Android介面實現】Drawable Animation 使用介紹,androiddrawable

    轉載請註明出處:http://blog.csdn.net/zhaokaiqiang1992

    (目前只能用在View對象上的動畫效果的實現有兩種,一種就是上一篇的View Animation,即補間動畫,剩下的一種,就是這一篇要介紹的,Drawable Animation,即幀動畫。在最新版本的API中,出現了一個更加強大的方式,PropertyAnimation,即屬性動畫,稍後將會介紹)

    Drawable animation允許我們一張一張的載入Drawable資源。這是一種傳統的動畫方式,通過一系列不同圖片的順序播放,可以製造齣電影一樣的效果。AnimationDrawable類是實現這種動畫效果的基類。

    用AnimationDrawable提供的API,我們當然可以在代碼中定義想要展示的每一幀的圖片,但是使用xml來列出我們想要展現的圖片的方式更加的方便。如果採用xml的方式,我們需要在res/drawable檔案下面建立,然後在xml檔案裡面指定我們要展示的每一幀的圖片資源和持續的時間。

    XML檔案由<animation-list>作為根節點元素,在根節點裡面,是一系列的<item>的子節點,在子節點裡面定義了要展示的圖片和每一幀持續的時間。下面是一個使用XML檔案定義Drawable Animation的一個執行個體。

<animation-list xmlns:android="http://schemas.android.com/apk/res/android"    android:oneshot="true">    <item android:drawable="@drawable/rocket_thrust1" android:duration="200" />    <item android:drawable="@drawable/rocket_thrust2" android:duration="200" />    <item android:drawable="@drawable/rocket_thrust3" android:duration="200" /></animation-list>

    這個動畫只會展示3幀的動畫,通過設定android:oneshot屬性為true,動畫只會播放一次然後就停止,並且會一直顯示最後一張圖片。如果我們設定成false,那麼動畫就會一直迴圈播放。我們把這個檔案儲存在/res/drawable/rocket_thrust.xml,然後我們就可以給一張View對象添加動畫的背景圖片。下面是一個Activity的樣本,我們給一個Imageview添加了動畫效果,然後當點擊時候,動畫開始播放。

AnimationDrawable rocketAnimation;public void onCreate(Bundle savedInstanceState) {  super.onCreate(savedInstanceState);  setContentView(R.layout.main);  ImageView rocketImage = (ImageView) findViewById(R.id.rocket_image);  rocketImage.setBackgroundResource(R.drawable.rocket_thrust);  rocketAnimation = (AnimationDrawable) rocketImage.getBackground();}public boolean onTouchEvent(MotionEvent event) {  if (event.getAction() == MotionEvent.ACTION_DOWN) {    rocketAnimation.start();    return true;  }  return super.onTouchEvent(event);}

    有一點非常重要,就是AnimationDrawable的start()方法不能夠在Activity的onCreate()調用,因為這個時候,AnimationDrawable可能還沒有完全的綁定到Window上。如果我們想馬上播放動畫,我們可以在onWindowFocusChanged()方法裡面調用,因為這個方法是在window已經擷取到焦點之後回調的,可以保證已經綁定結束。

    如果想瞭解

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在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.