Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 技術基礎

8.4.3 屬性動畫入門:ValueAnimator 與 ObjectAnimator

編輯:Android 技術基礎

本節導讀

本節談 Android 的第三種動畫——屬性動畫(Property Animation)。

先釐清一個常見混淆點。上一節為 Fragment 設定過場動畫時提過:App 套件與 V4 套件下的 Fragment,setCustomAnimations() 接受的動畫類型不同——v4 套件用 Animation,app 套件用 Animator。

Animation 就是我們前面學的frame 動畫與補間動畫;Animator 則是本節的屬性動畫。兩者的根本差異在於:補間動畫只是「對圖形做變換,View 本身的屬性其實沒變」,而屬性動畫是真的去改物件的屬性值。

這個主題郭霖(郭神)已有三篇非常完整的系列文:《Android 屬性動畫完全解析(上)初識屬性動畫的基本用法》、《(中)ValueAnimator 和 ObjectAnimator 的高級用法》、《(下)Interpolator 和 ViewPropertyAnimator 的用法》。本文大部分內容參考這三篇,讀完本文後若想深入,直接看那三篇是最快的路。


一、屬性動畫的核心概念

一句話總結:屬性動畫是「對某個物件的某個屬性,在指定時長內從 A 值連續變化到 B 值」,而在變化過程中你可以透過監聽器即時把新值套用到畫面上。


二、ValueAnimator 基本用法

標準四步驟

  1. 呼叫 ofInt()、ofFloat() 或 ofObject() 建立 ValueAnimator 實例。
  2. 呼叫 setXxx 設定 duration、interpolator、repeatCount 等參數。
  3. 呼叫 addUpdateListener() 註冊 AnimatorUpdateListener,於回呼中取得算出的值並套用到目標物件。
  4. 呼叫 start() 啟動動畫。

另外注意:ofInt 與 ofFloat 都接受多個中間值(float... values),可以讓數值走多段折線,例如 ofFloat(1f, 0.5f, 1.5f, 1f)。

實作範例

activity_main.xml:四顆按鈕加一個 ImageView。

<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:id="@+id/ly_root"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">
    <Button android:id="@+id/btn_one" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="動畫1" />
    <Button android:id="@+id/btn_two" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="動畫2" />
    <Button android:id="@+id/btn_three" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="動畫3" />
    <Button android:id="@+id/btn_four" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:text="動畫4" />
    <ImageView android:id="@+id/img_babi" android:layout_width="wrap_content"
        android:layout_height="wrap_content" android:layout_gravity="center"
        android:background="@mipmap/img_babi" />
</LinearLayout>

MainActivity.java:這裡示範四種效果——直線移動、縮放、旋轉加淡出、圓周旋轉。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_one, btn_two, btn_three, btn_four;
    private LinearLayout ly_root;
    private ImageView img_babi;
    private int width;
    private int height;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bindViews();
    }

    private void bindViews() {
        ly_root = (LinearLayout) findViewById(R.id.ly_root);
        btn_one = (Button) findViewById(R.id.btn_one);
        btn_two = (Button) findViewById(R.id.btn_two);
        btn_three = (Button) findViewById(R.id.btn_three);
        btn_four = (Button) findViewById(R.id.btn_four);
        img_babi = (ImageView) findViewById(R.id.img_babi);
        btn_one.setOnClickListener(this);
        btn_two.setOnClickListener(this);
        btn_three.setOnClickListener(this);
        btn_four.setOnClickListener(this);
        img_babi.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_one:   lineAnimator();   break;
            case R.id.btn_two:   scaleAnimator();  break;
            case R.id.btn_three: raAnimator();     break;
            case R.id.btn_four:  circleAnimator(); break;
            case R.id.img_babi:
                Toast.makeText(MainActivity.this, "不愧是 coder-pig~", Toast.LENGTH_SHORT).show();
                break;
        }
    }

    // 直接改變 View 的位置:呼叫 layout() 重新配置四邊
    private void moveView(View view, int rawX, int rawY) {
        int left = rawX - img_babi.getWidth() / 2;
        int top = rawY - img_babi.getHeight();
        int width = left + view.getWidth();
        int height = top + view.getHeight();
        view.layout(left, top, width, height);
    }

    // 動畫一:直線移動
    private void lineAnimator() {
        width = ly_root.getWidth();
        height = ly_root.getHeight();
        ValueAnimator xValue = ValueAnimator.ofInt(
                height, 0, height / 4, height / 2, height / 4 * 3, height);
        xValue.setDuration(3000L);
        xValue.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int y = (Integer) animation.getAnimatedValue();
                int x = width / 2;   // x 固定,只讓 y 變化
                moveView(img_babi, x, y);
            }
        });
        xValue.setInterpolator(new LinearInterpolator());
        xValue.start();
    }

    // 動畫二:縮放(示範組合動畫)
    private void scaleAnimator() {
        final float scale = 0.5f;
        AnimatorSet scaleSet = new AnimatorSet();

        ValueAnimator valueAnimatorSmall = ValueAnimator.ofFloat(1.0f, scale);
        valueAnimatorSmall.setDuration(500);
        ValueAnimator valueAnimatorLarge = ValueAnimator.ofFloat(scale, 1.0f);
        valueAnimatorLarge.setDuration(500);

        ValueAnimator.AnimatorUpdateListener listener =
                new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                float scale = (Float) animation.getAnimatedValue();
                img_babi.setScaleX(scale);
                img_babi.setScaleY(scale);
            }
        };
        valueAnimatorSmall.addUpdateListener(listener);
        valueAnimatorLarge.addUpdateListener(listener);

        scaleSet.play(valueAnimatorLarge).after(valueAnimatorSmall);
        scaleSet.start();

        // 其實一段就能搞定,拆兩段只是為了示範组合写法:
        // ValueAnimator vValue = ValueAnimator.ofFloat(1.0f, 0.6f, 1.2f, 1.0f, 0.6f, 1.2f, 1.0f);
        // vValue.setDuration(1000L);
        // vValue.addUpdateListener(...);
        // vValue.setInterpolator(new LinearInterpolator());
        // vValue.start();
    }

    // 動畫三:旋轉的同時改變透明度
    private void raAnimator() {
        ValueAnimator rValue = ValueAnimator.ofInt(0, 360);
        rValue.setDuration(1000L);
        rValue.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                int rotateValue = (Integer) animation.getAnimatedValue();
                img_babi.setRotation(rotateValue);
                // getAnimatedFraction() 就是 Interpolator 加工後的完成度
                float fractionValue = animation.getAnimatedFraction();
                img_babi.setAlpha(fractionValue);
            }
        });
        rValue.setInterpolator(new DecelerateInterpolator());
        rValue.start();
    }

    // 動畫四:圓周運動
    protected void circleAnimator() {
        width = ly_root.getWidth();
        height = ly_root.getHeight();
        final int R = width / 4;

        ValueAnimator tValue = ValueAnimator.ofFloat(0, (float) (2.0f * Math.PI));
        tValue.setDuration(1000);
        tValue.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
            @Override
            public void onAnimationUpdate(ValueAnimator animation) {
                // 圓的參數方程:x = R·sin(t),y = R·cos(t)
                float t = (Float) animation.getAnimatedValue();
                int x = (int) (R * Math.sin(t) + width / 2);
                int y = (int) (R * Math.cos(t) + height / 2);
                moveView(img_babi, x, y);
            }
        });
        tValue.setInterpolator(new DecelerateInterpolator());
        tValue.start();
    }
}

整組流程反覆都是同一套:建立 ValueAnimator → 設定時長 → addUpdateListener → 用 getAnimatedValue() 取當前值去改 View 屬性 → setInterpolator 決定速度 → start()。

寫到這裡不禁感嘆:直線方程、圓的參數方程……這些都是數學課的東西。 做動畫真的會被迫把三角函數撿回來。

範例參考自 GitHub 專案 MoveViewValueAnimator。


三、ObjectAnimator:更進一步的簡化

ValueAnimator 需要你自己接監聽器、自己把值套到物件上。ObjectAnimator 把這一步也包辦了——直接對任意物件的任意屬性做動畫,不限於 View。

典型寫法:

ObjectAnimator.ofFloat(textview, "alpha", 1f, 0f);

它會不斷把 alpha 從 1f 推向 0f,並且在每次值變動時自動呼叫對應的 setter 來更新畫面,淡入淡出於焉完成。

這裡有個關鍵觀念:TextView 類別裡其實沒有一個叫 alpha 的成員變數(你可以去翻源碼確認)。ObjectAnimator 的內部機制是:依你傳入的屬性名稱,反射尋找對應的 getXxx / setXxx 方法,而不是找同名欄位。所以屬性名稱必須與方法名稱嚴格對應,拼錯字只會在執行期拋异常。

public class MainActivity extends AppCompatActivity implements View.OnClickListener {
    private Button btn_one, btn_two, btn_three, btn_four, btn_five;
    private LinearLayout ly_root;
    private TextView tv_pig;
    private int height;
    private ObjectAnimator animator1, animator2, animator3, animator4;
    private AnimatorSet animSet;

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

    private void bindViews() {
        ly_root = (LinearLayout) findViewById(R.id.ly_root);
        btn_one = (Button) findViewById(R.id.btn_one);
        btn_two = (Button) findViewById(R.id.btn_two);
        btn_three = (Button) findViewById(R.id.btn_three);
        btn_four = (Button) findViewById(R.id.btn_four);
        btn_five = (Button) findViewById(R.id.btn_five);
        tv_pig = (TextView) findViewById(R.id.tv_pig);
        height = ly_root.getHeight();
        btn_one.setOnClickListener(this);
        btn_two.setOnClickListener(this);
        btn_three.setOnClickListener(this);
        btn_four.setOnClickListener(this);
        btn_five.setOnClickListener(this);
        tv_pig.setOnClickListener(this);
    }

    // 預先建立四條動畫
    private void initAnimator() {
        animator1 = ObjectAnimator.ofFloat(tv_pig, "alpha", 1f, 0f, 1f, 0f, 1f);
        animator2 = ObjectAnimator.ofFloat(tv_pig, "rotation", 0f, 360f, 0f);
        animator3 = ObjectAnimator.ofFloat(tv_pig, "scaleX", 2f, 4f, 1f, 0.5f, 1f);
        animator4 = ObjectAnimator.ofFloat(tv_pig, "translationY", height / 8, -100, height / 2);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_one:
                animator1.setDuration(3000l); animator1.start(); break;
            case R.id.btn_two:
                animator2.setDuration(3000l); animator2.start(); break;
            case R.id.btn_three:
                animator3.setDuration(3000l); animator3.start(); break;
            case R.id.btn_four:
                animator4.setDuration(3000l); animator4.start(); break;
            case R.id.btn_five:
                // 組合:先跑 animator1,同時跑 2、3、4
                animSet = new AnimatorSet();
                animSet.play(animator4).with(animator3).with(animator2).after(animator1);
                animSet.setDuration(5000l);
                animSet.start();
                break;
            case R.id.tv_pig:
                Toast.makeText(MainActivity.this, "不愧是 coder-pig~", Toast.LENGTH_SHORT).show();
                break;
        }
    }
}

四、組合動畫與事件監聽

AnimatorSet 的四種串接方式

呼叫 play() 並傳入第一個動畫後,會得到一個 Builder:

接著用這四個方法組合其他動畫:

  • after(Animator anim):排在傳入動畫之後執行。
  • after(long delay):延遲指定毫秒後執行。
  • before(Animator anim):排在傳入動畫之前執行。
  • with(Animator anim):與傳入動畫同時執行。

兩種監聽器

AnimatorUpdateListener:數值變化時回呼 onAnimationUpdate(),這是 ValueAnimator 的主力監聽器。

AnimatorListener:動畫生命周期監聽,需覆寫四個方法:

  • onAnimationStart():動畫開始
  • onAnimationRepeat():動畫重複
  • onAnimationEnd():動畫結束
  • onAnimationCancel():動畫取消

若只用到其中一兩個回呼,可以改用官方提供的適配器類別 AnimatorListenerAdapter,它已把介面方法全部實作為空實作,只需覆寫你要的那一個。


五、用 XML 撰寫動畫

寫 XML 的時間不一定比 Java 短,但重複使用時輕鬆很多。三個主要標籤:<animator>、<objectAnimator>、<set>。

常見屬性:

  • android:ordering:子動畫的播放順序,sequentially(順序)或 together(同時)。
  • android:duration:持續時間。
  • android:propertyName:屬性名稱,例如 "alpha"、"x"。目標物件必須有對應的 getX/setX。
  • android:valueFrom / android:valueTo:起始值與結束值。
  • android:valueType:值的型別,intType 或 floatType。

① 從 0 平滑過渡到 100

<animator xmlns:android="https://schemas.android.com/apk/res/android"
    android:valueFrom="0"
    android:valueTo="100"
    android:valueType="intType"/>

② 把 alpha 從 1 變成 0

<objectAnimator xmlns:android="https://schemas.android.com/apk/res/android"
    android:valueFrom="1"
    android:valueTo="0"
    android:valueType="floatType"
    android:propertyName="alpha"/>

③ set 組合動畫

<set android:ordering="sequentially" >
    <set>
        <objectAnimator
            android:duration="500"
            android:propertyName="x"
            android:valueTo="400"
            android:valueType="intType" />
        <objectAnimator
            android:duration="500"
            android:propertyName="y"
            android:valueTo="300"
            android:valueType="intType" />
    </set>
    <objectAnimator
        android:duration="500"
        android:propertyName="alpha"
        android:valueTo="1f" />
</set>

載入並執行

AnimatorSet set = (AnimatorSet) AnimatorInflater.loadAnimator(mContext, R.animator.property_animator);
set.setTarget(view);
set.start();

XML 方式記得補上 setTarget(),這是最容易漏掉的一步——少了它就會出現「動畫載入成功但什麼都沒發生」的情況。


本節回顧

屬性動畫的入門路徑其實很單純:ValueAnimator 給你「值」,你自己決定怎麼用;ObjectAnimator 幫你把「值 → setter → 畫面」這段自動化;AnimatorSet 負責把多條動畫組合成序列或並行。三者搭配,幾乎能做出任何你想要的過渡效果。

下一節我們會繼續談 Evaluator、Interpolator 與 ViewPropertyAnimator,把速度曲線與自訂型別這兩塊拼圖補上。

感謝郭神的系列文章。

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