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

Android 圖片閃爍動畫實作:用 animation-list 做幀動畫

編輯:關於 Android 程式設計

做法概述

Android 的幀動畫靠 animation-list 資源檔描述,再搭配 AnimationDrawable 在程式碼中啟動,非常適合做「錄影中」閃爍提示、載入指示這類簡單循環動畫。

一、定義動畫資源

建立 res/drawable/remote_recording_transition.xml:

<?xml version="1.0" encoding="utf-8"?>
<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
    android:oneshot="false">

    <item android:drawable="@drawable/remote_recording"
          android:duration="800" />
    <item android:drawable="@drawable/remote_recording_run"
          android:duration="800" />
</animation-list>

二、屬性說明

  • android:oneshot:是否只播放一次。false 為循環播放,true 只播一遍後停在最後一幀。
  • android:duration:該幀停留的間隔時間,單位是毫秒。這裡每幀 800ms,兩幀一輪共 1.6 秒。
  • item 的順序:就是播放順序,可以放入任意數量。

三、Java 程式碼啟動動畫

private AnimationDrawable recordingTransition;

recording = (ImageView) findViewById(R.id.recording);
recording.setBackgroundResource(R.drawable.remote_recording_transition);

recordingTransition = (AnimationDrawable) recording.getBackground();
recordingTransition.start();

四、幾個實務眉角

  • 要在 UI 執行緒啟動:幀動畫不支援在 onCreate() 中直接 start,因為此時背景可能尚未完成初始化,會出現「Drawable 沒有 callback」的錯誤。常見解法是放在 onResume(),或用 View 的 post() 延後一輪訊息迴圈再啟動。
  • 記得 stop:在 onPause() 中呼叫 recordingTransition.stop(),避免畫面不可見時仍在反覆切換圖片浪費資源。
  • 素材尺寸要一致:所有幀建議使用相同尺寸,否則會出現抖動或位置偏移。
  • 幀數與檔案大小:幀動畫會把所有圖片載入記憶體,幀數多、解析度高時記憶體佔用可觀。若動畫較長或較複雜,改用 ValueAnimator/ObjectAnimator 或 AnimatedVectorDrawable 會更省資源。
  • 也可用程式碼組裝:若幀素材是動態決定的,可用 AnimationDrawable.addFrame(drawable, duration) 在執行期動態加入。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved