編輯:關於 Android 程式設計
屬性動畫系統是 Android 3.0 起提供的一套管線,威力在於它能對任何物件的屬性做動畫,不管該屬性會不會被畫到螢幕上。傳統的 View 動畫只能改動繪製結果,屬性動畫則是直接改寫物件上的欄位值,讓目標在指定時間內從起始值過渡到結束值。
先看一個最簡單的例子:某個假想物件要動畫它的 x 座標(也就是螢幕上的水平位置),duration 設為 40ms,移動距離 40px。每 10ms 刷新一次,也就是每幀水平推進 10px;40ms 結束時停在 x=40。這是線性插值,等速移動。

圖 1:線性動畫
若改成非線性插值,同樣是 40ms 走 40px,但開頭加速、結尾減速。整段距離一樣,起訣與終點附近走的距離明顯小於中段。

圖 2:非線性動畫
這套計算由三個角色協作完成:

圖 3:動畫的計算流程
ValueAnimator 負責計時:它知道動畫已經跑了多久,也能算出當前屬性值。TimeInterpolator 定義插值方式,TypeEvaluator 定義如何依型別計算屬性值。以圖 2 為例,插值器是 AccelerateDecelerateInterpolator,評估器是 IntEvaluator。
計算過程分兩步。首先 ValueAnimator 依「已過時間 / 總時長」算出經過分數(0 到 1),0 代表 0%、1 代表 100%;圖 1 中 t=10ms 時是 0.25。接著把這個分數交給 TimeInterpolator 轉成插值分數;圖 2 因為開頭慢,t=10ms 的插值分數約 0.15,小於 0.25。最後由 TypeEvaluator 依插值分數算出該幀的實際屬性值,並呼叫 ValueAnimator.AnimatorUpdateListener 把值套用到目標物件上。
最直觀的用法:
ValueAnimator animation = ValueAnimator.ofFloat(0f, 1f);
animation.setDuration(1000);
animation.start();
這段程式會在 1000ms 內計算 0 到 1 之間的值。若要動畫自訂型別,則搭配自訂的 TypeEvaluator:
ValueAnimator animation = ValueAnimator.ofObject(new MyTypeEvaluator(),
startPropertyValue, endPropertyValue);
animation.setDuration(1000);
animation.start();
但要注意:ValueAnimator 本身不會改動任何物件。它只是把值算出來,剩下的套用動作要你自己在 AnimatorUpdateListener 裡透過 getAnimatedValue() 完成。
ObjectAnimator 是 ValueAnimator 的子類別,把計時引擎與「直接更新目標屬性」的能力結合起來,因此不必再自己寫 AnimatorUpdateListener:
ObjectAnimator anim = ObjectAnimator.ofFloat(foo, "alpha", 0f, 1f);
anim.setDuration(1000);
anim.start();
要讓它正常運作,有幾個前提:
setPropertyName()(駝峰式)。屬性名是 foo,就得有 setFoo()。若沒有,你可以幫目標類別補上、寫一個包裝類別轉發,或者退回使用 ValueAnimator。getPropertyName()。targetObject.setPropName(float) 與 getPropName() 回傳 float。invalidate()。反之,View 內建的 setter 如 setAlpha()、setTranslationX() 已經處理好失效重繪,不必多此一舉。很多時候動畫之間有先後依賴。AnimatorSet 可以把它們綁在一起,指定並行、序列或延遲:
AnimatorSet bouncer = new AnimatorSet();
bouncer.play(bounceAnim).before(squashAnim1);
bouncer.play(squashAnim1).with(squashAnim2);
bouncer.play(squashAnim1).with(stretchAnim1);
bouncer.play(squashAnim1).with(stretchAnim2);
bouncer.play(bounceBackAnim).after(stretchAnim2);
ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f);
fadeAnim.setDuration(250);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(bouncer).before(fadeAnim);
animatorSet.start();
更完整的示範可參考 API Demos 裡的 Bouncing Balls。
Animator.AnimatorListener:
onAnimationStart():動畫啟動。onAnimationEnd():動畫結束。被取消的動畫也會觸發。onAnimationRepeat():動畫重播。onAnimationCancel():動畫被取消。ValueAnimator.AnimatorUpdateListener:
onAnimationUpdate():每一幀都會呼叫,用 getAnimatedValue() 取出當前值。使用 ValueAnimator 時這個監聽器是必需的。若只想實作其中一兩個方法,繼承 AnimatorListenerAdapter 會比直接實作介面輕鬆:
ValueAnimator fadeAnim = ObjectAnimator.ofFloat(newBall, "alpha", 1f, 0f);
fadeAnim.setDuration(250);
fadeAnim.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
balls.remove(((ObjectAnimator) animation).getTarget());
}
});
LayoutTransition 可以為容器內子 View 的出現與消失加上動畫,共四種事件:
透過 setAnimator() 傳入自訂的 Animator 即可替換外觀;什麼都不設就使用系統預設。
最省力的做法是直接在 XML 上打開開關:
<LinearLayout
android:orientation="vertical"
android:layout_width="wrap_content"
android:layout_height="match_parent"
android:id="@+id/verticalContainer"
android:animateLayoutChanges="true" />
設為 true 之後,容器內子 View 的新增、刪除以及剩餘 View 的位移都會自動帶上版面轉場動畫。
系統內建的評估器有 IntEvaluator、FloatEvaluator 與 ArgbEvaluator。型別不在其中時,自己實作 TypeEvaluator 介面即可,唯一要寫的是 evaluate():
public class FloatEvaluator implements TypeEvaluator<Object> {
public Object evaluate(float fraction, Object startValue, Object endValue) {
float startFloat = ((Number) startValue).floatValue();
float endFloat = ((Number) endValue).floatValue();
return startFloat + fraction * (endFloat - startFloat);
}
}
特別注意:傳進 evaluate() 的 fraction 已經是插值後的分數,所以你不必在評估器裡再考慮插值器的存在。
插值器決定「時間 → 進度」的映射。系統在 android.view.animation 中提供了 AccelerateDecelerateInterpolator、AccelerateInterpolator、AnticipateInterpolator、OvershootInterpolator、BounceInterpolator、CycleInterpolator、DecelerateInterpolator、LinearInterpolator 等常用實作,不夠用就實作 TimeInterpolator。
以預設的兩個為例:
// AccelerateDecelerateInterpolator
public float getInterpolation(float input) {
return (float) (Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
}
// LinearInterpolator
public float getInterpolation(float input) {
return input;
}
以 1000ms 的動畫比較兩者:
| 已過時間 | 經過分數 / 線性插值分數 | 加減速插值分數 |
|---|---|---|
| 0 | 0 | 0 |
| 200 | 0.2 | 0.1 |
| 400 | 0.4 | 0.345 |
| 600 | 0.6 | 0.8 |
| 800 | 0.8 | 0.9 |
| 1000 | 1 | 1 |
線性版本每 200ms 穩定推進 0.2;加減速版本在 200–600ms 之間走得比線性快,頭尾則明顯放慢。
Keyframe 是「時間 / 值」對,讓你能在動畫的特定時刻定義特定狀態,每個 keyframe 還能帶自己的插值器:
Keyframe kf0 = Keyframe.ofFloat(0f, 0f);
Keyframe kf1 = Keyframe.ofFloat(.5f, 360f);
Keyframe kf2 = Keyframe.ofFloat(1f, 0f);
PropertyValuesHolder pvhRotation =
PropertyValuesHolder.ofKeyframe("rotation", kf0, kf1, kf2);
ObjectAnimator rotationAnim =
ObjectAnimator.ofPropertyValuesHolder(target, pvhRotation);
rotationAnim.setDuration(5000);
在屬性動畫之前,View 動畫只改變「繪製方式」,View 本身的屬性並未變動,於是會出現「畫面已經移走、點擊範圍卻還在原地」的怪異行為。Android 3.0 補上了新的屬性與對應的 getter/setter:
要動畫其中任何一個,只需建立對應的屬性動畫:
ObjectAnimator.ofFloat(myView, "rotation", 0f, 360f);
同時動畫多個屬性時,用多個 ObjectAnimator 會相對囉嗦:
// 寫法一:多個 ObjectAnimator 組合成 AnimatorSet
ObjectAnimator animX = ObjectAnimator.ofFloat(myView, "x", 50f);
ObjectAnimator animY = ObjectAnimator.ofFloat(myView, "y", 100f);
AnimatorSet animSetXY = new AnimatorSet();
animSetXY.playTogether(animX, animY);
animSetXY.start();
// 寫法二:單一 ObjectAnimator + 多個 PropertyValuesHolder
PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("x", 50f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", 100f);
ObjectAnimator.ofPropertyValuesHolder(myView, pvhX, pvhY).start();
而 ViewPropertyAnimator 一行就能搞定,並且共用底層 Animator,效率更好:
myView.animate().x(50f).y(100f);
屬性動畫的 XML 檔要放在 res/animator/(不是 res/anim/)。這樣做的好處是動畫可跨 Activity 複用,也更容易編輯序列。
對應標籤為:<animator>(ValueAnimator)、<objectAnimator>(ObjectAnimator)、<set>(AnimatorSet)。
<set android:ordering="sequentially">
<set>
<objectAnimator
android:propertyName="x"
android:duration="500"
android:valueTo="400"
android:valueType="intType" />
<objectAnimator
android:propertyName="y"
android:duration="500"
android:valueTo="300"
android:valueType="intType" />
</set>
<objectAnimator
android:propertyName="alpha"
android:duration="500"
android:valueTo="1f" />
</set>
執行時要把 XML 載入成 AnimatorSet,設定目標後啟動。setTarget() 可以一次指定所有子動畫的目標:
AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(myContext, R.animator.property_animator);
set.setTarget(myObject);
set.start();
把這幾塊拼起來看,屬性動畫的心智模型其實很單純:ValueAnimator 管時間,TimeInterpolator 管節奏,TypeEvaluator 管型別換算,ObjectAnimator 與 ViewPropertyAnimator 則負責把結果寫回物件。理解這條分工,剩下的 API 都只是排列組合。
Android 學習筆記:Activity 狀態保存與主題皮膚設定
本篇筆記整理兩個重點:Activity 的狀態保存機制,以及如何透過 android:theme 為 Activity 設定主題皮膚。 一、Activity 狀態的保存
Android 開發實戰(十一):SQLite 數據庫的完整用法
SQLite 是一款輕量級的關聯式數據庫,執行效率高、佔用資源極少,通常僅需數百 KB 的記憶體即可運行,並且完整支援標準 SQL 語法與 ACID 事務特性。在 And
Android 日誌收集與上報系統的設計思路
幾乎每一位應用開發者都明白「使用者體驗」的重量,但要提升體驗,前提是你得先知道問題出在哪裡。這就離不開一套完備的監控與上報機制,而其中最根本的一環,就是日誌——特別是 C
Android-Image-Cropper 相簿裁剪框架學習
Android-Image-Cropper 是一個常見的開源圖片裁剪框架。它提供裁剪檢視、觸控縮放、固定比例與旋轉等功能,適合需要頭像上傳、商品圖裁切或社群貼文的應用。