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

Android 屬性動畫完全指南:從 XML 到代碼,再到 Keyframe 進階用法

編輯:關於 Android 程式設計

相比補間動畫,屬性動畫(Property Animation)是更徹底的一套方案,它的兩個核心特點是:

  • 改變的是物件真實的屬性值,而不只是畫面上的變換。
  • 作用範圍不限於 View。任何提供了 getter 與 setter 方法的物件都能被動畫驅動。

這兩點差異,決定了屬性動畫能做出補間動畫做不到的事情——例如讓自訂物件中的某個計數值隨動畫遞增,並即時反映到介面上。

方式一:在 XML 中定義

屬性動畫的 XML 檔案放在 res/animator 目錄下(注意不是 res/anim,兩者不可混用)。

透明度:animator_alpha.xml

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="2000"
    android:propertyName="alpha"
    android:repeatCount="1"
    android:repeatMode="reverse"
    android:valueFrom="1.0"
    android:valueTo="0.2"
    android:valueType="floatType" />

背景色變化:animator_background.xml

顏色屬於非浮點、非整數型的值,需要使用 argbType,並搭配 ArgbEvaluator 做插值:

<?xml version="1.0" encoding="utf-8"?>
<objectAnimator xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="3000"
    android:propertyName="backgroundColor"
    android:valueFrom="#FF0000"
    android:valueTo="#0000FF"
    android:valueType="argbType"
    android:repeatCount="infinite"
    android:repeatMode="reverse" />

組合動畫:animator_set.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:ordering="together">
    <!-- ordering 可取 together(同時)或 sequentially(依序) -->
    <objectAnimator
        android:duration="2000"
        android:propertyName="scaleX"
        android:valueFrom="0"
        android:valueTo="2"
        android:valueType="floatType" />
    <objectAnimator
        android:duration="2000"
        android:propertyName="scaleY"
        android:valueFrom="0"
        android:valueTo="2"
        android:valueType="floatType" />
</set>

把動畫套用到控制項上

載入時用 AnimatorInflater,套用前必須先指定目標物件:

Animator animator = AnimatorInflater.loadAnimator(this, R.animator.animator_alpha);
animator.setTarget(mImage);
animator.start();

封裝成一個切換方法就更整齊了:

public class PropertyAnimXMLActivity extends AppCompatActivity {
    private ImageView mImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_property_anim_xml);
        mImage = (ImageView) findViewById(R.id.image);
    }

    public void onClick(View view) {
        Animator animator;
        switch (view.getId()) {
            case R.id.btn_alpha:
                animator = AnimatorInflater.loadAnimator(this, R.animator.animator_alpha); break;
            case R.id.btn_background:
                animator = AnimatorInflater.loadAnimator(this, R.animator.animator_background); break;
            case R.id.btn_set:
                animator = AnimatorInflater.loadAnimator(this, R.animator.animator_set); break;
            default:
                return;
        }
        animator.setTarget(mImage);
        animator.start();
    }
}

方式二:直接在 Java 代碼中定義

代碼方式的核心是 ObjectAnimator.ofFloat(),第一個參數是目標物件,第二個是屬性名,後面則是關鍵值序列。

public class PropertyAnimCodeActivity extends AppCompatActivity {
    private ImageView mImage;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_property_anim_code);
        mImage = (ImageView) findViewById(R.id.image);
    }

    public void onClick(View view) {
        ObjectAnimator animator;
        switch (view.getId()) {
            case R.id.btn_alpha:
                animator = ObjectAnimator.ofFloat(mImage, "alpha", 1, 0, 0.5f);
                break;
            case R.id.btn_translation:
                // 多個關鍵值會自動均分時間軸
                animator = ObjectAnimator.ofFloat(mImage, "translationX", 0, 50, 20, 60, 30);
                break;
            case R.id.btn_rotate:
                animator = ObjectAnimator.ofFloat(mImage, "rotation", 0, 360, 180, -180);
                break;
            case R.id.btn_scale:
                animator = ObjectAnimator.ofFloat(mImage, "scaleX", 0, 1, 0, 2);
                break;
            case R.id.btn_background:
                // 顏色動畫要用 ofObject 並提供 TypeEvaluator
                animator = ObjectAnimator.ofObject(mImage, "backgroundColor",
                        new ArgbEvaluator(), Color.RED, Color.GRAY, Color.BLUE);
                break;
            case R.id.btn_set:
                AnimatorSet set = new AnimatorSet();
                ObjectAnimator oaX = ObjectAnimator.ofFloat(mImage, "scaleX", 0, 2);
                ObjectAnimator oaY = ObjectAnimator.ofFloat(mImage, "scaleY", 0, 4);
                // propertyName 的首字母大小寫都可以
                set.setTarget(mImage);
                set.setDuration(2000);
                set.playTogether(oaX, oaY);
                // set.playSequentially(oaX, oaY); 依序執行
                // set.play(oaX).after(oaY);       巢狀組合:
                //   after(Animator) 排在指定動畫之後
                //   after(long)     延遲指定毫秒
                //   before(Animator)排在指定動畫之前
                //   with(Animator)  與指定動畫同時
                set.addListener(new Animator.AnimatorListener() {
                    @Override public void onAnimationStart(Animator a) { }
                    @Override public void onAnimationEnd(Animator a) { }
                    @Override public void onAnimationCancel(Animator a) { }
                    @Override public void onAnimationRepeat(Animator a) { }
                });
                set.start();
                return;
            default:
                return;
        }
        animator.setRepeatCount(1);
        animator.setRepeatMode(ValueAnimator.REVERSE);
        animator.setDuration(2000);
        animator.start();
        // 只需關注部分回調時,用 AnimatorListenerAdapter 更省事
        animator.addListener(new AnimatorListenerAdapter() {
            @Override
            public void onAnimationEnd(Animator animation) {
                super.onAnimationEnd(animation);
                Toast.makeText(PropertyAnimCodeActivity.this, "動畫結束", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

幾個容易忽略的進階用法

1. 屬性名就是 setter 方法名的去掉 set 前綴。如果物件上有 setValue(int),那麼屬性名就是 "value"。首字母大小寫隨意,但後續字母必須與 setter 中保持一致,寫錯不會報錯,只會靜默失效。

2. 用 Keyframe 精確控制時間軸。當關鍵值需要非等距分布時,Keyframe 是更好的選擇。它的時間以 0 到 1 之間的小數表示,對應動畫進度的百分比。

3. 用 AnimatorUpdateListener 讀取即時值。這個回調在每一幀都會觸發,可以拿到當前屬性值並更新到介面上,是做數字滾動、進度同步的常用手法。

public class PropertyAnimSpecialActivity extends AppCompatActivity {
    private TextView mTvTitle;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_property_anim_special);
        mTvTitle = (TextView) findViewById(R.id.tv_title);
    }

    @TargetApi(Build.VERSION_CODES.LOLLIPOP)
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.btn_colorValue:
                // ofArgb 是 API 21 提供的便捷方法,內部已封裝 ArgbEvaluator
                ObjectAnimator colorAnim = ObjectAnimator.ofArgb(mTvTitle, "textColor",
                        Color.RED, Color.YELLOW, Color.GREEN, Color.BLUE, Color.BLACK);
                colorAnim.setDuration(5000).start();
                colorAnim.addUpdateListener(animation -> {
                    int current = mTvTitle.getCurrentTextColor();
                    mTvTitle.setText("#" + Integer.toHexString(current));
                });
                break;

            case R.id.btn_value:
                // 屬性動畫的真正威力:作用於任意物件
                Test target = new Test();
                ObjectAnimator valueAnim = ObjectAnimator.ofInt(target, "value", 0, 100000);
                valueAnim.setDuration(5000).start();
                valueAnim.addUpdateListener(animation -> mTvTitle.setText(
                        animation.getAnimatedValue() + "------" + target.getValue()));
                break;

            case R.id.btn_keyFrames:
                // 第一個參數是時間比例(0~1),第二個是該時刻的值
                Keyframe kf1 = Keyframe.ofInt(0f, 0);
                Keyframe kf2 = Keyframe.ofInt(0.25f, 50);
                Keyframe kf3 = Keyframe.ofInt(0.5f, 100);
                Keyframe kf4 = Keyframe.ofInt(0.75f, 150);
                Keyframe kf5 = Keyframe.ofInt(1.0f, 200);
                PropertyValuesHolder holder =
                        PropertyValuesHolder.ofKeyframe("value", kf1, kf2, kf3, kf4, kf5);
                ObjectAnimator keyframeAnim =
                        ObjectAnimator.ofPropertyValuesHolder(target, holder);
                keyframeAnim.setDuration(3000).start();
                break;
            default:
                break;
        }
    }

    // 自訂物件只要具備 getter / setter 即可被動畫驅動
    public static class Test {
        private int value;

        public int getValue() {
            return value;
        }

        public void setValue(int value) {
            // 這裡可以印一段 Log,就能觀察到 ObjectAnimator 每一幀都在呼叫 setter
            this.value = value;
        }
    }
}

理解到這一層,屬性動畫就不再只是「讓 View 動起來」的工具,而是一套通用的「數值隨時間變化」框架。把動畫目標從 View 換成資料模型,很多原本需要寫計時器的業務(進度增長、數字翻滾、模擬物理量變化)都能用同一套 API 優雅解決。

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