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

一次搞懂 Android 三種動畫:補間、幀動畫與屬性動畫

編輯:關於 Android 開發

Android 的動畫體系其實是分批長出來的。3.0 之前只有兩種:對應 SDK 中 View Animation 的補間動畫(Tween Animation),以及對應 Drawable Animation 的幀動畫(Frame Animation);3.0 之後才加入功能更強大的屬性動畫(Property Animation)。搞不清楚三者界線,寫出來的動畫常常會出現「畫面動了但點擊位置沒動」這類怪象,所以先把分類理清楚很重要。


一、補間動畫(res/anim/)

補間動畫的做法是給定兩個關鍵幀,再由系統用插值演算法把屬性值在指定時間內從起點漸變到終點。它可以用 XML 定義,也可以在程式碼中建立 AlphaAnimation、ScaleAnimation、TranslateAnimation、RotateAnimation 等物件。

特性與限制:只能作用在 View 上,而且只支援少數幾種屬性。更關鍵的是,它並不改變物件的真實屬性,只改變了 View 被繪製出來的樣子——按鈕動畫結束後看起來換了位置,但點擊事件的命中區域仍然留在原本的座標上。

XML 的第一層必須是單一根節點,可以是 <alpha>(漸變)、<scale>(伸縮)、<translate>(位移)、<rotate>(旋轉),或者用 <set> 把多個動畫打包成動畫集。

<!-- res/anim/scale.xml -->
<set android:shareInterpolator="false">
    <scale
        android:interpolator="@android:anim/accelerate_decelerate_interpolator"
        android:fromXScale="1.0"
        android:toXScale="1.4"
        android:fromYScale="1.0"
        android:toYScale="0.6"
        android:pivotX="50%"
        android:pivotY="50%"
        android:fillAfter="false"
        android:duration="700" />
</set>

程式碼中觸發的步驟固定三步:載入動畫物件、設定時長(XML 裡也可直接寫)、啟動動畫。

ImageView image = (ImageView) findViewById(R.id.spaceshipImage);
Animation anim = AnimationUtils.loadAnimation(this, R.anim.hyperspace_jump);
image.startAnimation(anim);

插值器(Interpolator)決定了動畫的節奏曲線,可以做出加速、減速、重複、回彈等效果。這類資源放在 res/anim 下,透過 android:interpolator="@android:anim/..." 引用。

二、幀動畫(res/drawable/)

幀動畫的原理最樸素:把一連串圖片依序播放,靠視覺殘像形成動畫,程式碼中對應的類別是 AnimationDrawable。

<animation-list xmlns:android="https://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>

根節點必須是 <animation-list>,每個 <item> 代表要輪播的一張圖,duration 是該幀停留的毫秒數。

imageView = (ImageView) findViewById(R.id.imageView1);
imageView.setBackgroundResource(R.drawable.drawable_anim);
anim = (AnimationDrawable) imageView.getBackground();

// 觸發時
anim.stop();
anim.start();

三個實務上的地雷:

  • 背景資源要在程式碼中呼叫 setBackgroundResource() 設定;若直接在 XML 佈局裡寫 src,動畫啟動時會直接閃退。
  • start() 之前一定要先 stop(),否則第一次播放完會停在最後一幀,之後再也動不起來。
  • 不要在 onCreate() 裡直接 start()。此時 AnimationDrawable 尚未與 Window 完全關聯;若希望畫面一出現就播放,改在 onWindowFocusChanged() 中啟動。

三、屬性動畫(res/animator/,3.0 之後)

屬性動畫改變的是物件的真實屬性值:Button 縮放後,它的位置與大小屬性確實被改寫了。它也不侷限於 View,幾乎任何物件都能套用,甚至不需要真的畫在螢幕上——本質上它只負責「讓某個值在一段時間內變化」,值變了之後要做什麼,完全由你自己決定。

可以自訂的項目包括:

  • Duration:動畫時長,預設 300 ms。
  • Time interpolation:數值計算方式,例如先快後慢。
  • Repeat count and behavior:重複次數與重複模式。
  • Animator sets:動畫集合,可讓多段動畫同時播放或設定時間偏移。
  • Frame refresh delay:刷新間隔,預設 10 ms,實際會受系統調度與硬體影響。

ValueAnimator:核心引擎

ValueAnimator 幾乎涵蓋了屬性動畫的所有核心能力:時長、起訖值、對應時間的數值計算等。使用它時,第一步(產生並驅動數值)它已經幫你做完了,你只需要實作 onUpdateListener,決定每次數值變化時要做什麼。

ValueAnimator anim = ValueAnimator.ofFloat(0f, 1f);
anim.setDuration(1000);
anim.addUpdateListener(animation -> {
    float value = (Float) animation.getAnimatedValue();
    tv.setTranslationX(value);
});
anim.setInterpolator(new CycleInterpolator(3));
anim.start();

ObjectAnimator:少寫兩步的懶人版

ObjectAnimator 是 ValueAnimator 的子類,它替你完成了「把值寫回物件」這一步。但要讓它正確運作,目標物件必須符合幾個約定:

  • 必須有對應的 setter 方法,命名遵循駝峰式:setter<PropertyName>。若屬性叫 foo,就要有 setFoo(),否則只能退回 ValueAnimator。
  • 像 ofFloat() 這類靜態工廠,第一個參數是目標物件,第二個是屬性名稱,後面是可變參數。若只傳了一個值,系統會把它當作終值,變化區間就是「目前值 → 終值」;而為了取得目前值,物件必須提供 get<PropertyName>。
  • getter 的傳回型別必須與 setter 的參數型別一致。
btn.setOnClickListener(v -> {
    ObjectAnimator anim = ObjectAnimator.ofFloat(tv, "alpha", 0f, 1f);
    anim.setDuration(3000);
    anim.start();
});

部分情況下(例如自繪 View),你可能需要在 onAnimationUpdate() 回呼中呼叫 invalidate() 強制重繪。

AnimatorSet:安排動畫的時間序列

動畫集可以指定多段動畫的播放關係:同時、先後銜接等。

AnimatorSet bouncer = new AnimatorSet();
bouncer.play(bounceAnim).before(squashAnim1);
bouncer.play(squashAnim1).with(squashAnim2);
bouncer.play(squashAnim1).with(stretchAnim1);
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();

動畫監聽與一個省字的小技巧

Animator.AnimatorListener 定義了動畫生命週期:onAnimationStart()、onAnimationEnd()、onAnimationRepeat(),以及取消時的 onAnimationCancel()(取消後仍會接著觸發 onAnimationEnd())。

如果只在意其中一兩個回呼,繼承 AnimatorListenerAdapter 會比實作介面清爽得多——這個類別已經把每個方法都實作為空實體,你只覆寫需要的即可。

ObjectAnimator anim = ObjectAnimator.ofFloat(tv, "alpha", 0f, 1f);
anim.setDuration(3000);
anim.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        Log.i("Animation", "end");
    }
});
anim.start();

ViewGroup 的過渡動畫

只要給容器加上 android:animateLayoutChanges="true",在增刪子 View 時就會自動播放過渡動畫。

<LinearLayout
    android:id="@+id/verticalContainer"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:animateLayoutChanges="true" />

常見的四種過渡類型:

  • LayoutTransition.APPEARING:某個 View 出現時,套用在它自己身上的動畫。
  • LayoutTransition.CHANGE_APPEARING:某個 View 出現後擠動了其他 View,套用在其他 View身上的動畫。
  • LayoutTransition.DISAPPEARING:某個 View 消失時,套用在它自己身上的動畫。
  • LayoutTransition.CHANGE_DISAPPEARING:某個 View 消失後其他 View 補位,套用在其他 View身上的動畫。

View.animate() 與 ViewPropertyAnimator

API 12 起可以直接用 View.animate() 串起整段動畫,還能掛上開始與結束的 Runnable:

imageView.animate()
        .alpha(0f)
        .y(50)
        .setDuration(1000)
        .withStartAction(() -> Log.e(TAG, "START"))
        .withEndAction(() -> {
            Log.e(TAG, "END");
            runOnUiThread(() -> {
                imageView.setY(0);
                imageView.setAlpha(1.0f);
            });
        })
        .start();

ViewPropertyAnimator 特別適合「同一個 View、多個屬性同時動」的場景。它內部會合併多次 invalidate(),大幅減少重繪次數,效能明顯優於逐一啟動多個動畫。

PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f, 0f, 1f);
PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("y", 50, 0);
ObjectAnimator.ofPropertyValuesHolder(mBlueBall, pvhX, pvhY)
        .setDuration(1000)
        .start();

TypeEvaluator:自訂數值計算規則

Evaluator 的工作是根據起始值、結束值,以及插值器算出的時間因子,求出當下的屬性值。系統內建 IntEvaluator(int)、FloatEvaluator(float)、ArgbEvaluator(十六進位顏色),也可以實作 TypeEvaluator 介面自訂。

public class FloatEvaluator implements TypeEvaluator<Float> {
    @Override
    public Float evaluate(float fraction, Float startValue, Float endValue) {
        // fraction 由動畫時間與 Interpolator 共同算出,落在 0~1 之間
        return startValue + fraction * (endValue - startValue);
    }
}

用 XML 描述屬性動畫

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:propertyName="scaleX"
    android:valueFrom="1.0"
    android:valueTo="2.0"
    android:valueType="floatType" />
public void scaleX(View view) {
    Animator anim = AnimatorInflater.loadAnimator(this, R.animator.scalex);
    anim.setTarget(mMv);
    anim.start();
}

簡單講:需要「讓某個 View 看起來動一下」用補間動畫就夠;要播放序列圖片用幀動畫;而只要涉及真實狀態改變、自訂物件或複合動畫,屬性動畫才是正解。

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