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

Android 補間動畫 TweenAnimation 用法整理

編輯:Android 程式設計入門

補間動畫(Tween Animation)是 Android 最直覺的動畫方案:你只要描述「從哪個狀態變到哪個狀態、花多久時間」,系統就會自動補上中間的過渡影格。以下把程式碼動態建立與 XML 靜態宣告兩種寫法都整理出來。

一、載入 XML 動畫資源

animation_translate = AnimationUtils.loadAnimation(MainActivity.this, R.anim.transalte);
imageview.startAnimation(animation_translate);

把動畫寫在 res/anim 下可以讓它與邏輯分離,設計師或後端協作者也能自行調整參數,是比較推薦的做法。

二、組合多種動畫:AnimationSet

AnimationSet set = new AnimationSet(true);
// true:整組共用同一套時間軸;false:各自獨立計時
set.addAnimation(animation_alpha);
set.addAnimation(animation_rotate);
set.addAnimation(animation_scale);
set.addAnimation(animation_translate);
set.setDuration(4000);
set.setRepeatCount(AnimationSet.INFINITE);
set.setRepeatMode(AnimationSet.REVERSE);
imageview.startAnimation(set);

AnimationSet 的建構參數是個容易搞錯的細節:傳 true 代表整組共用一個 Interpolator 與時間基準,傳 false 則讓每個子動畫各自跑自己的節奏。

三、純程式碼建立旋轉動畫

RotateAnimation rotate = new RotateAnimation(
        0, 360,
        Animation.RELATIVE_TO_SELF, 0.5f,
        Animation.RELATIVE_TO_SELF, 0.5f);
rotate.setDuration(3000);
rotate.setRepeatCount(RotateAnimation.INFINITE);
imageview.startAnimation(rotate);

後四個參數決定旋轉中心。RELATIVE_TO_SELF 搭配 0.5f,就是「以自己寬高的一半為軸心」,也就是繞著正中央旋轉。若改成 ABSOLUTE,則 0.5f 會被解讀成像素值,效果完全不同。

四、XML 宣告的寫法

<set xmlns:android="https://schemas.android.com/apk/res/android">

    <alpha android:fromAlpha="0.0"
           android:toAlpha="1.0"
           android:duration="3000"
           android:repeatCount="infinite" />

    <rotate android:fromDegrees="0"
            android:toDegrees="360"
            android:pivotX="50%"
            android:pivotY="50%"
            android:duration="4000"
            android:repeatCount="infinite" />

    <translate android:fromXDelta="0"
               android:toXDelta="300"
               android:fromYDelta="0"
               android:toYDelta="300"
               android:repeatCount="infinite"
               android:duration="5000" />

    <scale android:fromXScale="0.5"
           android:toXScale="1"
           android:fromYScale="0.5"
           android:toYScale="1"
           android:pivotX="50%"
           android:pivotY="50%"
           android:repeatCount="infinite"
           android:duration="4000" />

</set>

五、幾個實務提醒

  • 補間動畫不改變真實位置:平移只是視覺上的位移,View 實際的點擊區域並不會跟著移動。若需要真正的互動位移,應改用 ObjectAnimator 等屬性動畫。
  • 動畫結束後會回原樣:預設情況下 View 會跳回起點,要保留終態得設定 fillAfter。
  • 為 translate 加上單位:XML 中 android:toXDelta="300" 是像素,在不同 dpi 的機子上視覺幅度差很多,正式專案建議搭配 dimen 資源或改用百分比寫法。
  • 記得在 onStop 清除動畫:無限重複的動畫若不在 Activity 離開時停止,會白白消耗電力。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved