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

Android 屬性動畫(Property Animation)完全解析(上):從 ObjectAnimator 到 AnimatorSet

編輯:關於 Android 程式設計

Android 提供了三類動畫機制:View Animation、Drawable Animation 與 Property Animation。View Animation 上手極快,但能力邊界也很清楚——它只支援縮放、平移、旋轉、透明度這幾種基本變換,而且是「改動畫,不改屬性」。這帶來幾個繞不過去的限制:想做顏色漸變、想做 3D 翻轉、希望動畫結束後 View 就真的停在該位置——這些 View Animation 都做不到。

Property Animation 就是為了解決這些問題而出現的。本篇完整梳理它的 API 與實作方式;至於 Drawable Animation,嗯,略。

一、先掌握五個屬性

Property Animation 的本質是「用動畫的方式改變物件的屬性值」。要控制它,先認識這五個參數:

Duration——動畫持續時間,預設 300ms。

Time interpolation——時間插值。聽名字有點抽象,但說到 LinearInterpolator、AccelerateDecelerateInterpolator 大家就懂了,它定義的是「變化速率曲線」。

Repeat count and behavior——重複次數與重複模式,可以設定重複幾次,以及重複時是從頭再來還是反向播放。

Animator sets——動畫集合,可以把一組動畫組織成同時執行或依序執行。

Frame refresh delay——影格刷新延遲,多久刷新一次,預設 10ms,最終仍取決於系統當前負載,實務上基本不用管。

二、相關類別

ObjectAnimator 與 ValueAnimator 是兩個執行類,差別在於是否直接綁定目標屬性,後面詳談。AnimatorSet 負責控制一組動畫的執行次序。AnimatorInflater 用來從 XML 載入屬性動畫。TypeEvaluator 負責把「時間比例」換算成「屬性值」。TimeInterpolator 則是上面提過的插值器。

一句話總結:執行類設定操作對象、屬性、持續時間、起訖值與插值方式,系統便依這些參數逐幀改寫物件屬性。

三、ObjectAnimator:一行完成動畫

之所以從它講起,是因為它最簡單。版面檔只放一張圖:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/id_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/id_ball"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:onClick="rotateyAnimRun"
        android:scaleType="centerCrop"
        android:src="@drawable/mv" />
</RelativeLayout>

Activity 這邊,真的就是一行:

public class ObjectAnimActivity extends Activity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.xml_for_anim);
    }

    public void rotateyAnimRun(View view) {
        ObjectAnimator.ofFloat(view, "rotationX", 0.0F, 360.0F)
                .setDuration(500)
                .start();
    }
}

關於 ObjectAnimator 的三個必知規則

規則一:ofInt、ofFloat、ofObject 三個方法的意義相同——設定作用的物件、作用的屬性名稱、以及開始、結束與中間任意個屬性值。只給一個值時,系統會以「該物件此屬性的當前值」為起點(透過 getter 反射取得),給兩個值則分別為起點與終點。

規則二:屬性必須有 setter,只給一個值時還必須有 getter。因為動畫進行的過程中,系統會不斷呼叫 setPropName 去更新物件屬性。少了 setter,動畫看起來會「跑完但什麼都沒發生」,這是新手最常撞的牆。

規則三:setter 內部若沒有觸發重繪,你要自己補。

anim.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        view.postInvalidate();
    }
});

進階玩法:一個 ObjectAnimator 動多個屬性

如果希望同一個動畫同時讓 View 縮小並淡出(scaleX、scaleY、alpha 三個屬性),直覺答案是用 AnimatorSet。但這裡示範另一條路:讓 ObjectAnimator 去動一個「假屬性」,我們只取它算出的時間序列值,自己動手套用。

public void rotateyAnimRun(final View view) {
    ObjectAnimator anim = ObjectAnimator.ofFloat(view, "zhy", 1.0F, 0.0F)
            .setDuration(500);
    anim.addUpdateListener(new AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            float cVal = (Float) animation.getAnimatedValue();
            view.setAlpha(cVal);
            view.setScaleX(cVal);
            view.setScaleY(cVal);
        }
    });
}

關鍵在於:那個屬性名稱寫什麼都無所謂,我們要的只是「依插值與時長算出的當前值」。這個思路很有用——例如想做拋物線運動(水平 100px/s、垂直加速度 200px/s²),也可以照這個模式自行試出來。不要被 API 表面綁住。

更乾淨的做法:PropertyValuesHolder

public void propertyValuesHolder(View view) {
    PropertyValuesHolder pvhX = PropertyValuesHolder.ofFloat("alpha", 1f, 0f, 1f);
    PropertyValuesHolder pvhY = PropertyValuesHolder.ofFloat("scaleX", 1f, 0, 1f);
    PropertyValuesHolder pvhZ = PropertyValuesHolder.ofFloat("scaleY", 1f, 0, 1f);
    ObjectAnimator.ofPropertyValuesHolder(view, pvhX, pvhY, pvhZ)
            .setDuration(1000)
            .start();
}

這才是官方提供的正解:多組屬性值收在同一個動畫裡,共享同一條時間軸,不必玩假屬性的把戲。

四、ValueAnimator:把控制權交回自己手上

用法看似類似:

public void verticalRun(View view) {
    ValueAnimator animator = ValueAnimator.ofFloat(0, mScreenHeight - mBlueBall.getHeight());
    animator.setTarget(mBlueBall);
    animator.setDuration(1000).start();
}

但仔細看會發現:沒有指定任何屬性。所以上面這段其實不會產生任何視覺效果。

這正是它與 ObjectAnimator 的根本差異:ValueAnimator 只在數值上做運算,不碰物件屬性。好處是不再需要目標屬性具備 getter/setter,你可以依當前計算值去操作任何東西——上一節那個「同時縮小與淡出」的需求,用 ValueAnimator 就是最自然的解法。

實例一:自由落體

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:id="@+id/id_container"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <ImageView
        android:id="@+id/id_ball"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/bol_blue">

        <LinearLayout
            android:layout_width="fill_parent"
            android:layout_height="wrap_content"
            android:layout_alignParentBottom="true"
            android:orientation="horizontal">
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="verticalRun"
                android:text="垂直" />
            <Button
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:onClick="paowuxian"
                android:text="拋物線" />
        </LinearLayout>
    </ImageView>
</RelativeLayout>
/** 自由落體 */
public void verticalRun(View view) {
    ValueAnimator animator = ValueAnimator.ofFloat(0, mScreenHeight - mBlueBall.getHeight());
    animator.setTarget(mBlueBall);
    animator.setDuration(1000);
    // animator.setInterpolator(value)
    animator.addUpdateListener(new AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            mBlueBall.setTranslationY((Float) animation.getAnimatedValue());
        }
    });
    animator.start();
}

比 ObjectAnimator 多了幾行,但換來的是完全的控制權:屬性怎麼更新、更新哪一個,都由你決定。

實例二:拋物線,需要自訂 TypeEvaluator

拋物線的難點在於:橫向與縱向的移動速率不同,而我們需要在同一時間點同時拿到 x 與 y 兩個值。這時就該自訂 TypeEvaluator。

/** 拋物線 */
public void paowuxian(View view) {
    ValueAnimator valueAnimator = new ValueAnimator();
    valueAnimator.setDuration(3000);
    valueAnimator.setObjectValues(new PointF(0, 0));
    valueAnimator.setInterpolator(new LinearInterpolator());
    valueAnimator.setEvaluator(new TypeEvaluator<PointF>() {
        // fraction = t / duration
        @Override
        public PointF evaluate(float fraction, PointF startValue, PointF endValue) {
            // x 方向 200px/s,則 y 方向為 0.5 * 200 * t^2
            PointF point = new PointF();
            point.x = 200 * fraction * 3;
            point.y = 0.5f * 200 * (fraction * 3) * (fraction * 3);
            return point;
        }
    });
    valueAnimator.start();
    valueAnimator.addUpdateListener(new AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            PointF point = (PointF) animation.getAnimatedValue();
            mBlueBall.setX(point.x);
            mBlueBall.setY(point.y);
        }
    });
}

因為 ofInt/ofFloat 無法一次回傳兩個值,我們自訂了一個 TypeEvaluator,讓它在每個時間點回傳一個 PointF。PointF 與 Point 的區別就是 x、y 的單位一為 float 一為 int(RectF 與 Rect 同理),這裡需要小數精度所以選 PointF。泛型參數可依需求自行設計成任何 Bean。

五、監聽動畫事件

動畫多半是輔助效果。例如要刪除一個元素時做淡出,但淡出結束後是真的要把它從容器移除——不能只是「看不見卻還佔位」。這就需要知道動畫何時結束。

public void fadeOut(View view) {
    ObjectAnimator anim = ObjectAnimator.ofFloat(mBlueBall, "alpha", 0.5f);
    anim.addListener(new AnimatorListener() {
        @Override
        public void onAnimationStart(Animator animation) { }

        @Override
        public void onAnimationRepeat(Animator animation) { }

        @Override
        public void onAnimationEnd(Animator animation) {
            ViewGroup parent = (ViewGroup) mBlueBall.getParent();
            if (parent != null) {
                parent.removeView(mBlueBall);
            }
        }

        @Override
        public void onAnimationCancel(Animator animation) { }
    });
    anim.start();
}

這樣就能掌握開始、結束、取消、重複等事件。但若你只在意結束,四個方法全實在有點囉嗦,這時可以改用 AnimatorListenerAdapter——它實作了 AnimatorListener 介面並把所有方法空實作,你只覆寫需要的那一個:

anim.addListener(new AnimatorListenerAdapter() {
    @Override
    public void onAnimationEnd(Animator animation) {
        ViewGroup parent = (ViewGroup) mBlueBall.getParent();
        if (parent != null) {
            parent.removeView(mBlueBall);
        }
    }
});

另外兩個容易搞混的方法:cancel() 讓動畫立即停止並停在當前位置,會觸發 onAnimationCancel 再觸發 onAnimationEnd;end() 則是直接跳到最終狀態,只觸發 onAnimationEnd。若你的結束處理會做「移除 View」這類不可回復的動作,要留意 cancel 也會走到 onAnimationEnd。

六、AnimatorSet:把多個動畫組織起來

public class AnimatorSetActivity extends Activity {

    private ImageView mBlueBall;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.anim_set);
        mBlueBall = (ImageView) findViewById(R.id.id_ball);
    }

    /** 兩個動畫同時執行 */
    public void togetherRun(View view) {
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(mBlueBall, "scaleX", 1.0f, 2f);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(mBlueBall, "scaleY", 1.0f, 2f);
        AnimatorSet animSet = new AnimatorSet();
        animSet.setDuration(2000);
        animSet.setInterpolator(new LinearInterpolator());
        animSet.playTogether(anim1, anim2);
        animSet.start();
    }

    /** 混合排序:1、2 同時,3 接在 2 之後,4 接在 3 之後 */
    public void playWithAfter(View view) {
        float cx = mBlueBall.getX();
        ObjectAnimator anim1 = ObjectAnimator.ofFloat(mBlueBall, "scaleX", 1.0f, 2f);
        ObjectAnimator anim2 = ObjectAnimator.ofFloat(mBlueBall, "scaleY", 1.0f, 2f);
        ObjectAnimator anim3 = ObjectAnimator.ofFloat(mBlueBall, "x", cx, 0f);
        ObjectAnimator anim4 = ObjectAnimator.ofFloat(mBlueBall, "x", cx);

        AnimatorSet animSet = new AnimatorSet();
        animSet.play(anim1).with(anim2);
        animSet.play(anim2).with(anim3);
        animSet.play(anim4).after(anim3);
        animSet.setDuration(1000);
        animSet.start();
    }
}

第一個方法用 playTogether 讓動畫同時跑,相對地也有 playSequentially 讓它們依序跑。第二個方法示範如何用程式碼控制複雜順序:with 表示同時、before 表示在前、after 表示在後。

這裡有個陷阱要注意:雖然 play().with() 支援鏈式寫法,但不要以為可以一路狂串——例如 play(anim1).with(anim2).before(anim3).before(anim5),系統不會依這串呼叫去推導整體的先後關係。請照範例的寫法,一行一行把關係寫清楚。

七、還剩下什麼

由於篇幅,還有幾個主題留待下篇:用 XML 檔案定義屬性動畫、版面動畫(Layout Transition),以及 View 上的 animate() 便捷方法。核心功能到這裡其實已經齊備。

最後補充一個實務提醒:若要支援 API 11 以下的版本,需導入 nineoldandroids 這個相容庫,用法幾乎完全一致。

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