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

Android 動畫入門指南(一):View Animation 與 LayoutAnimation 完整解析

編輯:關於 Android 開發

Android 動畫入門指南(一):View Animation 與 LayoutAnimation 完整解析

在 Android 開發中,動畫是提升使用者體驗的重要手段。本系列文章將系統梳理 Android 動畫的三大類別,而本篇作為開篇,重點介紹最基礎也最常用的 View Animation(視圖動畫)與 LayoutAnimation(布局動畫)。

一、Tween 補間動畫

Tween 動畫又被稱為補間動畫,它的核心思想是透過改變 View 的位置、尺寸、透明度與旋轉角度,來營造出運動的視覺效果。可以把它理解為:只需告訴系統動畫的起點與終點,中間的過渡幀會由系統自動「補」出來。

補間動畫的抽象基類是 Animation,日常開發中最常打交道的是它的四個直接子類:RotateAnimation(旋轉)、TranslateAnimation(平移)、ScaleAnimation(縮放)與 AlphaAnimation(漸變)。

這些動畫既可以用 XML 定義(放在 res/anim/ 目錄下),再透過 AnimationUtils 類加載;也可以完全使用程式碼動態建立,兩種方式各有適用場景。


XML 語法結構

<set android:interpolator="@[package:]anim/interpolator_resource"
    android:shareInterpolator="true"
    xmlns:android="https://schemas.android.com/apk/res/android">
    <alpha android:fromAlpha="float" android:toAlpha="float" />
    <scale android:fromXScale="float" android:fromYScale="float"
        android:pivotX="float" android:pivotY="float"
        android:toXScale="float" android:toYScale="float" />
    <translate android:fromXDelta="float" android:fromYDelta="float"
        android:toXDelta="float" android:toYDelta="float" />
    <rotate android:fromDegrees="float" android:pivotX="float"
        android:pivotY="float" android:toDegrees="float" />
</set>

Animation 類中預先定義了大量常量,例如:

public static final int INFINITE = -1;
public static final int RESTART = 1;
public static final int REVERSE = 2;

其中最重要的莫過於 AnimationListener 介面,它讓你能在動畫的不同階段插入自訂邏輯:

public static interface AnimationListener {
    /** 動畫開始時回調 */
    void onAnimationStart(Animation animation);
    /** 動畫結束時回調;若重複次數設為 INFINITE,則此方法不會被觸發 */
    void onAnimationEnd(Animation animation);
    /** 動畫重複播放時回調 */
    void onAnimationRepeat(Animation animation);
}

透過註冊這個監聽器,就能在動畫開始、結束或循環時執行額外操作。


插值器 Interpolator

在深入動畫之前,必須先理解「插值器」的概念。插值器決定了動畫播放的速率曲線——它可以讓動畫由慢到快、由快到慢,或者呈現回彈等效果。系統內建了九種常用插值器:

插值器子類 Resource ID 效果說明

AccelerateInterpolator @android:anim/accelerate_interpolator 加速變化,起步慢、越來越快
DecelerateInterpolator @android:anim/decelerate_interpolator 減速變化,起步快、越來越慢
AccelerateDecelerateInterpolator @android:anim/accelerate_decelerate_interpolator 先加速後減速,中段速度最快
LinearInterpolator @android:anim/linear_interpolator 線性勻速變化
OvershootInterpolator @android:anim/overshoot_interpolator 衝過終點值後再緩慢回到終值
AnticipateInterpolator @android:anim/anticipate_interpolator 先反向蓄力,再加速前進
AnticipateOvershootInterpolator @android:anim/anticipate_overshoot_interpolator 先反向蓄力,再衝過終值後回彈
BounceInterpolator @android:anim/bounce_interpolator 動畫尾段模擬小球落地的回彈
CycleInterpolator @android:anim/cycle_interpolator 以正弦曲線循環指定次數


自定義 Interpolator

官方提供的這九種插值器已經能滿足絕大多數需求,但如果想更細緻地控制節奏,也可以自定義插值器——最簡單的做法就是繼承系統插值器並微調其參數值。


公共 XML 屬性與對應方法

屬性名稱 對應方法 說明

android:duration / setDuration(long):動畫持續時間(毫秒)
android:interpolator / setInterpolator(Interpolator):設定插值器
android:repeatCount / setRepeatCount(int):動畫重複次數
android:repeatMode / setRepeatMode(int):重複模式(repeatCount 大於 0 時生效),可選 reverse(2) 或 restart(1)
android:startOffset / setStartOffset(long):動畫啟動的延遲時間
android:fillAfter / setFillAfter(boolean):設為 true 時,視圖停留在動畫結束狀態
android:fillBefore / setFillBefore(boolean):預設 true,視圖停留在動畫開始狀態
android:fillEnabled / setFillEnabled(boolean):預設 false;設為 true 時 fillBefore 才會生效
android:detachWallpaper / setDetachWallpaper(boolean):預設 false;設為 true 時動畫只作用於 window 而不影響壁紙
android:zAdjustment / setZAdjustment(int):調整動畫期間內容在 Z 軸方向的層疊順序

其中 zAdjustment 的三個取值分別是:normal(0) 保持當前 Z 軸順序;top(1) 強制置於最上層;bottom(-1) 強制置於最下層。


ScaleAnimation — 縮放動畫

XML 屬性 說明

android:fromXScale / toXScale:X 軸方向的起始與結束縮放比例。0.0 表示縮至消失,1.0 表示原始大小,大於 1.0 放大,小於 1.0 縮小
android:fromYScale / toYScale:Y 軸方向的起始與結束縮放比例
android:pivotX / pivotY:縮放中心點座標

縮放中心點的設定方式有三種:寫成 "50" 為絕對定位(Animation.ABSOLUTE);寫成 "50%" 為相對自身(Animation.RELATE_TO_SELF);寫成 "50%p" 為相對父容器(Animation.RELATE_TO_PARENT)。

以 XML 定義縮放動畫
<scale xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="1000"
    android:fillAfter="false"
    android:fillBefore="true"
    android:fromXScale="1" android:fromYScale="1"
    android:toXScale="0" android:toYScale="0"
    android:pivotX="50%" android:pivotY="50%"
    android:interpolator="@android:anim/accelerate_decelerate_interpolator"
    android:repeatCount="1" android:repeatMode="restart"
    android:startOffset="500" android:zAdjustment="bottom" />

再以 AnimationUtils 加載並套用:

Animation scaleAnimation = AnimationUtils.loadAnimation(this, R.anim.scale_anim);
targetIv.startAnimation(scaleAnimation);
以程式碼定義縮放動畫
ScaleAnimation scaleAnimation = new ScaleAnimation(
    1.0f, 0.5f, 1.0f, 0.5f,
    Animation.RELATIVE_TO_SELF, 0.5f,
    Animation.RELATIVE_TO_SELF, 0.5f);
scaleAnimation.setDuration(1000);
scaleAnimation.setInterpolator(new OvershootInterpolator());
scaleAnimation.setFillAfter(true);
targetIv.startAnimation(scaleAnimation);

ScaleAnimation 共有四個構造方法:

public ScaleAnimation(Context context, AttributeSet attrs) {}
public ScaleAnimation(float fromX, float toX, float fromY, float toY) {}
public ScaleAnimation(float fromX, float toX, float fromY, float toY, float pivotX, float pivotY) {}
public ScaleAnimation(float fromX, float toX, float fromY, float toY,
    int pivotXType, float pivotXValue, int pivotYType, float pivotYValue) {}

第一個構造用於從資源檔加載,日常開發主要使用前三者。若未指定 pivotXType 與 pivotYType,則預設採用 ABSOLUTE,此時 pivotX、pivotY 都是相對於左上角 (0,0) 的偏移量。pivotXType 的三種取值:ABSOLUTE(絕對值)、RELATE_TO_SELF(相對自身,範圍 0%~100%)、RELATE_TO_PARENT(相對父容器,範圍 0%~100%)。

效果如下:


RotateAnimation — 旋轉動畫

XML 屬性 說明

android:fromDegrees:起始角度(可正可負)
android:toDegrees:結束角度(可正可負)
android:pivotX / pivotY:旋轉中心點,設定方式與縮放動畫相同

以 XML 設定旋轉動畫
<rotate xmlns:android="https://schemas.android.com/apk/res/android"
    android:duration="2500"
    android:fillAfter="true"
    android:fromDegrees="-20" android:toDegrees="320"
    android:pivotX="50%" android:pivotY="50%"
    android:interpolator="@android:anim/overshoot_interpolator" />
以程式碼設定旋轉動畫
RotateAnimation rotateAnimation = new RotateAnimation(
    0.0f, 550.0f,
    Animation.RELATIVE_TO_SELF, 0.3f,
    Animation.RELATIVE_TO_SELF, 0.3f);
rotateAnimation.setDuration(1500);
rotateAnimation.setInterpolator(new OvershootInterpolator());
rotateAnimation.setFillAfter(true);
targetIv.startAnimation(rotateAnimation);

效果圖如下:


TranslateAnimation — 平移動畫

XML 屬性 說明

android:fromXDelta / toXDelta:平移的起始與結束 X 座標
android:fromYDelta / toYDelta:平移的起始與結束 Y 座標

以程式碼設定平移動畫
TranslateAnimation translateAnimation = new TranslateAnimation(0, 200, 0, 0);
translateAnimation.setDuration(1000);
translateAnimation.setInterpolator(new AnticipateOvershootInterpolator());
targetIv.startAnimation(translateAnimation);


AlphaAnimation — 漸變動畫

XML 屬性 說明

android:fromAlpha:動畫開始時的透明度
android:toAlpha:動畫結束時的透明度

以程式碼設定漸變動畫
AlphaAnimation alphaAnimation = new AlphaAnimation(1.0f, 0.2f);
alphaAnimation.setDuration(1500);
alphaAnimation.setInterpolator(new AccelerateDecelerateInterpolator());
alphaAnimation.setRepeatMode(Animation.REVERSE);
alphaAnimation.setRepeatCount(1);
targetIv.startAnimation(alphaAnimation);


AnimationSet — 動畫集合

前面介紹的都是單一動畫,實際專案裡往往需要把多個動畫組合播放,這就要用到 AnimationSet。它同樣可以在 XML 中定義,用 <set> 標籤包裹其他動畫即可。相比單一動畫,它多了一個 android:shareInterpolator="boolean" 屬性,用於控制子動畫是否共用同一個插值器。

以 XML 設定動畫集合
<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:fillAfter="true" android:shareInterpolator="false">
    <scale android:duration="1000"
        android:fromXScale="0.8" android:fromYScale="0.8"
        android:toXScale="0.3" android:toYScale="0.5"
        android:pivotX="60%" android:pivotY="20%"
        android:startOffset="1500"
        android:interpolator="@android:anim/linear_interpolator">
        <rotate android:duration="1000"
            android:fromDegrees="50" android:toDegrees="360"
            android:pivotX="50%p" android:pivotY="50%p"
            android:startOffset="3500"
            android:interpolator="@android:anim/anticipate_overshoot_interpolator" />
    </scale>
</set>

這裡有一個容易踩的坑:套用上述 set 動畫後,動畫啟動瞬間會先突然變小並旋轉一個角度,才開始正常播放。仔細排查後發現,這是因為動畫開始時把 scale 與 rotate 的初始狀態提前應用了。直覺上會想到 android:fillBefore 屬性,但在子動畫裡加上 fillBefore="false" 後仍然無效。查閱 Animation 源碼才發現,fillBefore 必須在 fillEnabled="true" 的前提下才會生效,而 fillBefore 預設值又恰好是 true,所以才會出現這種現象。修正後的寫法如下:

<set xmlns:android="https://schemas.android.com/apk/res/android"
    android:fillAfter="true" android:shareInterpolator="false">
    <scale android:duration="1000"
        android:fillBefore="false" android:fillEnabled="true"
        android:fromXScale="0.8" android:fromYScale="0.8"
        android:toXScale="0.3" android:toYScale="0.5"
        android:pivotX="60%" android:pivotY="20%"
        android:startOffset="1500"
        android:interpolator="@android:anim/linear_interpolator">
        <rotate android:duration="1000"
            android:fillBefore="false" android:fillEnabled="true"
            android:fromDegrees="50" android:toDegrees="360"
            android:pivotX="50%p" android:pivotY="50%p"
            android:startOffset="3500"
            android:interpolator="@android:anim/anticipate_overshoot_interpolator" />
    </scale>
</set>

效果如下:


二、Frame 幀動畫

Frame 動畫的原理是把多張圖片按順序一幀一幀播放出來,視覺效果類似 GIF。使用起來非常直觀:只需把每一幀的圖片依序加入,設定每幀的顯示時長,再將動畫套用到 View 上即可。

以 XML 設定幀動畫
<animation-list xmlns:android="https://schemas.android.com/apk/res/android">
    <item android:drawable="@drawable/person1" android:duration="100" />
    <item android:drawable="@drawable/person2" android:duration="100" />
    <item android:drawable="@drawable/person3" android:duration="100" />
    <item android:drawable="@drawable/person4" android:duration="100" />
    <item android:drawable="@drawable/person5" android:duration="100" />
    <item android:drawable="@drawable/person6" android:duration="100" />
    <item android:drawable="@drawable/person7" android:duration="100" />
</animation-list>

為 ImageView 套用動畫:

targetIv.setBackgroundResource(R.drawable.frame_anim);
AnimationDrawable animationDrawable = (AnimationDrawable) targetIv.getBackground();
animationDrawable.start();
以程式碼設定幀動畫
AnimationDrawable animationDrawable = new AnimationDrawable();
animationDrawable.setOneShot(false);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.person1), 200);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.person2), 200);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.person3), 200);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.person4), 200);
animationDrawable.addFrame(getResources().getDrawable(R.drawable.person5), 200);
targetIv.setImageDrawable(animationDrawable);
animationDrawable.start();


LayoutAnimationController

無論是 Tween Animation 還是 Frame Animation,作用的對象都是單個 View。而 LayoutAnimationController 的強大之處在於它能針對整個 ViewGroup 施加動畫,讓容器中的每個子 View 按照既定規則依次呈現動畫效果。最典型的場景就是為 ListView、GridView 或 RecyclerView 的每個 item 設計入場動畫,而不是讓它們一次性生硬地全部顯示。

實務上,ListView 通常搭配 layoutAnimation,GridView 搭配 gridLayoutAnimation。而 RecyclerView 一般只能用 layoutAnimation,直接套用 gridLayoutAnimation 會報錯——不過可以透過繼承 RecyclerView 並重寫相關方法來支援,這一點後文會詳細說明。

XML 屬性 對應方法 說明

android:delay / setDelay(float):動畫播放的延遲時間
android:animationOrder / setOrder(int):子 View 播放動畫的順序(如 normal)
android:interpolator / setInterpolator(Interpolator):插值器
android:animation / LayoutAnimationController(animation):指定子 View 的動畫

以 XML 定義 LayoutAnimation
<layoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:animation="@anim/item_list_anim"
    android:animationOrder="normal"
    android:delay="0.2"
    android:interpolator="@android:anim/bounce_interpolator" />
以程式碼定義 LayoutAnimation
public LayoutAnimationController(Animation animation) {
    this(animation, 0.5f);
}
public LayoutAnimationController(Animation animation, float delay) {
    mDelay = delay;
    setAnimation(animation);
}

LayoutAnimationController 常用上述兩個構造方法,其中 delay 表示每個子 View 啟動動畫的延遲時間,預設為 0.5f,單位為秒。

Animation animation = AnimationUtils.loadAnimation(this, R.anim.item_list_anim);
LayoutAnimationController layoutAnimationController = new LayoutAnimationController(animation);
layoutAnimationController.setInterpolator(new AccelerateInterpolator());
layoutAnimationController.setDelay(0.5f);
layoutAnimationController.setOrder(LayoutAnimationController.ORDER_RANDOM);
recyclerView.setLayoutAnimation(layoutAnimationController);


GridLayoutAnimationController

GridLayoutAnimationController 是 LayoutAnimationController 的子類,專門用於為 GridView 這類網格容器製作動畫。

XML 屬性 對應方法 說明

android:delay / setDelay(float):動畫播放的延遲時間
android:columnDelay / setColumnDelay(float):列播放動畫的延遲時間
android:rowDelay / setRowDelay(float):列播放動畫的延遲時間
android:animationOrder / setOrder(int):子 View 播放動畫的順序
android:animation / LayoutAnimationController(animation):指定子 View 的動畫

以 XML 定義
<gridLayoutAnimation xmlns:android="https://schemas.android.com/apk/res/android"
    android:animation="@anim/item_anim_alpha"
    android:columnDelay="0.5"
    android:direction="bottom_to_top|right_to_left"
    android:directionPriority="row" />
以程式碼設定

同樣是用一個 Animation 構造出 GridLayoutAnimationController 物件,設定各項參數後再套用到 GridView 即可。

Animation animation = AnimationUtils.loadAnimation(this, R.anim.item_anim_alpha);
GridLayoutAnimationController gridLayoutAnimationController = new GridLayoutAnimationController(animation);
gridLayoutAnimationController.setDirection(
    GridLayoutAnimationController.DIRECTION_BOTTOM_TO_TOP
    | GridLayoutAnimationController.DIRECTION_RIGHT_TO_LEFT);
gridLayoutAnimationController.setDirectionPriority(
    GridLayoutAnimationController.PRIORITY_ROW);
gridRecyclerView.setLayoutAnimation(gridLayoutAnimationController);

效果如下:


三、RecyclerView 擴展:支援 GridLayoutAnimation

正常情況下,RecyclerView 可以直接使用 LayoutAnimation。但若嘗試為它套用 GridLayoutAnimation,就會拋出以下異常:

java.lang.ClassCastException:
android.view.animation.LayoutAnimationController$AnimationParameters
cannot be cast to
android.view.animation.GridLayoutAnimationController$AnimationParameters
    at GridLayoutAnimationController.getDelayForView(...)
    at LayoutAnimationController.getAnimationForView(...)
    at ViewGroup.bindLayoutAnimation(...)
    at ViewGroup.dispatchDraw(...)

簡單說,就是 GridLayoutAnimationController.AnimationParameters 無法被強轉為 LayoutAnimationController.AnimationParameters。

RecyclerView 的誕生本來就是為了取代 ListView,同時它也能呈現 GridView 的效果,那麼如何讓它在搭配 GridLayoutManager 時也能套用 gridLayoutAnimation 動畫呢?先看看 GridView 是如何實作的。在 GridView 源碼中搜索 LayoutAnimation 關鍵字,會找到 attachLayoutAnimationParameters() 方法,它將 layoutAnimationParameters 強轉成了 GridLayoutAnimationController.AnimationParameters:

@Override
protected void attachLayoutAnimationParameters(View child, ViewGroup.LayoutParams params, int index, int count) {
    GridLayoutAnimationController.AnimationParameters animationParams =
        (GridLayoutAnimationController.AnimationParameters) params.layoutAnimationParameters;
    if (animationParams == null) {
        animationParams = new GridLayoutAnimationController.AnimationParameters();
        params.layoutAnimationParameters = animationParams;
    }
    animationParams.count = count;
    animationParams.index = index;
    animationParams.columnsCount = mNumColumns;
    animationParams.rowsCount = count / mNumColumns;
    if (!mStackFromBottom) {
        animationParams.column = index % mNumColumns;
        animationParams.row = index / mNumColumns;
    } else {
        final int invertedIndex = count - 1 - index;
        animationParams.column = mNumColumns - 1 - (invertedIndex % mNumColumns);
        animationParams.row = animationParams.rowsCount - 1 - invertedIndex / mNumColumns;
    }
}

接著我們到 RecyclerView 裡尋找 attachLayoutAnimationParameters() 方法,卻發現它並未重寫此方法,而是沿用了父類 ViewGroup 的實作:

protected void attachLayoutAnimationParameters(View child, LayoutParams params, int index, int count) {
    LayoutAnimationController.AnimationParameters animationParams = params.layoutAnimationParameters;
    if (animationParams == null) {
        animationParams = new LayoutAnimationController.AnimationParameters();
        params.layoutAnimationParameters = animationParams;
    }
    animationParams.count = count;
    animationParams.index = index;
}

由此可見,RecyclerView 預設只實作了 ViewGroup 的通用 LayoutAnimation。解決思路很清晰:自訂一個 RecyclerView 子類並重寫此方法,關鍵是要移除 mStackFromBottom 的判斷分支。

public class GridRecyclerView extends RecyclerView {
    public GridRecyclerView(Context context) { super(context); }
    public GridRecyclerView(Context context, AttributeSet attrs) { super(context, attrs); }
    public GridRecyclerView(Context context, AttributeSet attrs, int defStyle) { super(context, attrs, defStyle); }

    @Override
    public void setLayoutManager(LayoutManager layout) {
        if (layout instanceof GridLayoutManager) {
            super.setLayoutManager(layout);
        } else {
            throw new ClassCastException("you should only use the GridLayoutManager as LayoutManager when you use this "
                + this.getClass().getSimpleName() + " class");
        }
    }

    @Override
    protected void attachLayoutAnimationParameters(View child, ViewGroup.LayoutParams params, int index, int count) {
        if (getLayoutManager() != null && getLayoutManager() instanceof GridLayoutManager) {
            GridLayoutAnimationController.AnimationParameters animationParams =
                (GridLayoutAnimationController.AnimationParameters) params.layoutAnimationParameters;
            if (animationParams == null) {
                animationParams = new GridLayoutAnimationController.AnimationParameters();
                params.layoutAnimationParameters = animationParams;
            }
            int mNumColumns = ((GridLayoutManager) getLayoutManager()).getSpanCount();
            animationParams.count = count;
            animationParams.index = index;
            animationParams.columnsCount = mNumColumns;
            animationParams.rowsCount = count / mNumColumns;
            final int invertedIndex = count - 1 - index;
            animationParams.column = mNumColumns - 1 - (invertedIndex % mNumColumns);
            animationParams.row = animationParams.rowsCount - 1 - invertedIndex / mNumColumns;
        } else {
            super.attachLayoutAnimationParameters(child, params, index, count);
        }
    }
}

需要特別注意的是,搭配 GridLayoutManager 時不能使用 setStackFromEnd 屬性:

/**
 * stackFromEnd is not supported by GridLayoutManager. Consider using
 * {@link #setReverseLayout(boolean)}.
 */
@Override
public void setStackFromEnd(boolean stackFromEnd) {
    if (stackFromEnd) {
        throw new UnsupportedOperationException(
            "GridLayoutManager does not support stack from end. Consider using reverse layout");
    }
    super.setStackFromEnd(false);
}
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved