Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

用 Animation-list 實現 Android 逐幀動畫

編輯:關於 Android 程式設計

逐幀動畫是 Android 中相當實用的一種動畫形式,特別適合製作 loading 等循環播放的效果。它的實現非常簡單,只需透過一個 animation-list 描述檔把多張圖片串起來即可。下面一步步來看做法。

一、編寫 animation-list 描述檔

在 res/drawable 目錄下新增 loading.xml。根標籤為 animation-list,其中 oneshot 代表是否只播放一遍(設為 false 會不斷循環);每個 item 透過 android:duration 指定該幀的顯示時長:

<animation-list xmlns:android="https://schemas.android.com/apk/res/android" android:oneshot="false">
    <item android:drawable="@drawable/light01" android:duration="50" />
    <item android:drawable="@drawable/light02" android:duration="50" />
    <item android:drawable="@drawable/light03" android:duration="50" />
</animation-list>

二、在布局檔中使用

在 activity_main.xml 中放一個 ImageView 作為動畫載體,src 指向剛才的 loading.xml,並附上開始與停止按鈕:

<ImageView
    android:id="@+id/main_img_loading"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="5px"
    android:src="@drawable/loading" />

<Button
    android:id="@+id/main_bt_start"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="開始" />

<Button
    android:id="@+id/main_bt_stop"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="停止" />

三、在 Activity 中控制動畫

透過 AnimationDrawable 即可控制動畫的開始與停止:

bt_start.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        AnimationDrawable animationDrawable = (AnimationDrawable) animationIV.getDrawable();
        animationDrawable.start();  // 開始動畫
    }
});

bt_stop.setOnClickListener(new OnClickListener() {
    public void onClick(View v) {
        AnimationDrawable animationDrawable = (AnimationDrawable) animationIV.getDrawable();
        animationDrawable.stop();   // 停止動畫
    }
});

就這麼簡單,透過 animation-list 描述檔搭配 AnimationDrawable,就能輕鬆實現流暢的逐幀動畫效果。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved