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

Android 屬性動畫完全指南:從 ValueAnimator 到 AnimatorSet

編輯:關於 Android 程式設計

一、三種動畫,各自的位置

Android 提供了 View Animation、Drawable Animation 與 Property Animation 三套動畫體系。View Animation 最簡單,支援平移、縮放、旋轉、透明度等基本變換;Drawable Animation 分為逐幀與補間兩類;Property Animation 功能最強,某個角度可以視為補間動畫的強化版本。

屬性動畫需要定義的屬性如下:

  • 持續時間:預設 300 毫秒,資源檔中用 android:duration 指定。
  • 差值方式:作用與補間動畫的插值屬性類似,用來定義變化率,資源檔中用 android:interpolator 指定。
  • 重複次數:android:repeatCount。
  • 重複模式:決定下一輪是從頭再播,還是從結束幀反向播放,android:repeatMode。
  • 動畫集:把多個屬性動畫合成一組,可循序也可同時播放,資源檔中用 set 元素組合。
  • 幀刷新頻率:預設 10 毫秒一幀。

二、相關 API

  • Animator:屬性動畫的基底類別,實務上很少直接用,通常繼承後重寫需要的方法。
  • ValueAnimator:屬性動畫的時間引擎,負責計算每一幀的屬性值,並處理更新事件、依值型別決定計算規則。屬性動畫由兩件事組成:算出各幀的值、把值套用到目標物件。ValueAnimator 只做前者,所以開發者必須自己監聽值變化並更新物件。
  • ObjectAnimator:ValueAnimator 的子類,能直接對指定物件的屬性執行動畫。
  • AnimatorSet:Animator 的子類,用來組合多個動畫並安排播放順序。

屬性動畫還需要 Evaluator 決定「怎麼算」:

  • IntEvaluator:計算 int 型屬性值。
  • FloatEvaluator:計算 float 型屬性值。
  • ArgbEvaluator:計算以十六進位表示的顏色值。
  • TypeEvaluator:計算器介面,自訂計算規則時實作它。

三、用 ValueAnimator 實作動畫

步驟很固定:先用 ofInt()、ofFloat() 或 ofObject() 建立物件,再用 setXxx() 設定 duration、interpolator、repeatCount,然後 start() 啟動。但只做到這裡,畫面上什麼都不會發生——因為值還沒被套用到任何物件。

animator = ValueAnimator.ofFloat(0f, 300);
animator.setDuration(4000);
animator.start();

要看到效果,必須註冊 AnimatorUpdateListener,透過 getAnimatedValue() 取出當前幀的值,再自行套用:

animator.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        mImageView.setTranslationX((Float) animation.getAnimatedValue());
    }
});

若預設的計算規則不合用,也可以自訂 Evaluator:

animator = ValueAnimator.ofObject(new CustomEvaluator(), startVal, endVal);
animator.setDuration(1000);
animator.start();

四、用 ObjectAnimator 簡化流程

ObjectAnimator 繼承自 ValueAnimator,能把計算出的值直接套到指定屬性上,因此不需要再註冊 AnimatorUpdateListener。

public class ObjectAnimatorActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_object_animator);
    }

    public void changeAlpha(final View view) {
        ObjectAnimator anim = ObjectAnimator.ofFloat(view, "alpha", 1.0F, 0.2F);
        anim.setDuration(500);
        anim.start();
    }
}

使用 ObjectAnimator 有兩點要留意:

  • ofInt()、ofFloat()、ofObject() 的參數依序是「作用物件、作用屬性、起始值、結束值(以及任意個中間值)」。若只給一個值,該值會被當成結束值,起始值則透過 getter 反射取得,所以目標屬性必須有對應的 getter。
  • 若屬性的 setter 內部沒有觸發重繪,就必須在 onAnimationUpdate() 中自行呼叫 invalidate() 或 postInvalidate() 才能看到畫面更新。
anim.addUpdateListener(new AnimatorUpdateListener() {
    @Override
    public void onAnimationUpdate(ValueAnimator animation) {
        view.postInvalidate();
    }
});

一個動畫同時改多個屬性

直覺做法是 AnimatorSet,但只用 ObjectAnimator 也做得到。技巧是把屬性名稱換成一個實際不存在的字串,讓它單純作為「時間驅動器」,真正的套用動作自己寫:

public void changeAlpha(final View view) {
    ObjectAnimator anim = ObjectAnimator.ofFloat(view, "xmr", 1.0F, 0.2F);
    anim.setDuration(5000);
    anim.start();
    anim.addUpdateListener(new AnimatorUpdateListener() {
        @Override
        public void onAnimationUpdate(ValueAnimator animation) {
            float value = (Float) animation.getAnimatedValue();
            view.setAlpha(value);
            view.setScaleX(value);
            view.setScaleY(value);
        }
    });
}

更正式的作法是用 PropertyValuesHolder:

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

五、監聽動畫事件

動畫多半只是輔助效果。做淡出移除時,透明度歸零不代表可以就此了事,視圖還占著位置,必須在動畫真正結束後把它從父容器中移除。

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

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

如果只在意結束事件,用 AnimatorListenerAdapter 更省事——它實作了 AnimatorListener 介面並把方法都留成空實作:

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

六、AnimatorSet 的組合方式

同時播放用 playTogether,循序播放用 playSequentially:

public void togetherRun(View view) {
    ObjectAnimator anim1 = ObjectAnimator.ofFloat(mImageView, "scaleX", 1.0f, 2.0f);
    ObjectAnimator anim2 = ObjectAnimator.ofFloat(mImageView, "scaleY", 1.0f, 2.0f);

    AnimatorSet animSet = new AnimatorSet();
    animSet.setDuration(5000);
    animSet.setInterpolator(new LinearInterpolator());
    animSet.playTogether(anim1, anim2);
    animSet.start();
}

需要更細膩的排程時,用 play().with() 與 play().after():

public void playWithAfter(View view) {
    float cx = mImageView.getX();
    ObjectAnimator anim1 = ObjectAnimator.ofFloat(mImageView, "scaleX", 1.0f, 2.0f);
    ObjectAnimator anim2 = ObjectAnimator.ofFloat(mImageView, "scaleY", 1.0f, 2.0f);
    ObjectAnimator anim3 = ObjectAnimator.ofFloat(mImageView, "x", cx, 0.0f);
    ObjectAnimator anim4 = ObjectAnimator.ofFloat(mImageView, "x", cx);

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

最後提醒一個容易踩的坑:雖然 play().with() 支援鏈式呼叫,但不要把順序寫成一長串,例如 play(anim1).with(anim2).before(anim3).before(anim5)。系統不會照你寫的先後去排,結果往往不如預期。老實照範例那樣分成幾行寫,反而最可靠。

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