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

Android 動畫三部曲之一:View Animation 與 LayoutAnimation 完全解析

編輯:關於 Android 程式設計

Tween 補間動畫

Tween 動畫又稱補間動畫,是通過改變 View 的位置、大小、透明度與角度來實現動畫效果的一種方式。

補間動畫的基類是 Animation,我們通常使用它的直接子類 RotateAnimation、TranslateAnimation、ScaleAnimation 和 AlphaAnimation。

補間動畫既可以通過 XML 進行定義(res/anim/xxx),再用 AnimationUtils 類加載;也可以完全通過代碼進行設置。


XML 語法介紹

 
  
  
  
  
   ... 

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);
    void onAnimationEnd(Animation animation);
    void onAnimationRepeat(Animation animation);
}

添加此監聽器後,可以對動畫過程做更多細緻的控制。


插值器 – Interpolator

在介紹動畫之前,得先聊聊「插值器」。插值器的作用是在播放動畫時改變播放速率,可以讓動畫越來越快,或越來越慢。

常用的有以下九個插值器:

BaseInterpolator 子類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

一般來說,官方 API 提供的這幾個插值器已經足夠實用。不過我們也可以自定義 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 值,否則 fillBefore 的值會被忽略 android:detachWallpaper setDetachWallpaper(boolean) 默認值為 false,若為 true 且動畫窗體有壁紙,則動畫只應用於 window,牆紙保持靜止 android:zAdjustment setZAdjustment(int) 允許在動畫播放期間調整內容在 Z 軸方向的順序,"top"(1)、"normal"(0)或 "bottom"(-1)

其中 android:zAdjustment 的三種取值含義為:normal(0)保持當前 Z 軸順序;top(1)在動畫期間強制將當前內容置於其他內容之上;bottom(-1)則強制置於其他內容之下。


ScaleAnimation – 縮放動畫

XML 屬性名稱描述 android:fromXScale 動畫起始時 X 軸坐標的伸縮尺寸,0.0 表示收縮到無,1.0 表示正常,大於 1.0 放大,小於 1.0 收縮 android:toXScale 動畫結束時 X 軸坐標的伸縮尺寸 android:fromYScale 動畫起始時 Y 軸坐標的伸縮尺寸 android:toYScale 動畫結束時 Y 軸坐標的伸縮尺寸 android:pivotX 縮放作用點在 X 軸方向的位置,如 "50" 表示絕對定位,"50%" 表示相對控件本身,"50%p" 表示相對父控件 android:pivotY 縮放作用點在 Y 軸方向的位置
XML 定義縮放動畫
 

然後通過 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 表示絕對值,相對左上角偏移,如 android:pivotX="50";RELATIVE_TO_SELF 表示相對控件本身的相對值,如 "50%" 表示 X 方向中軸點位於正中,取值範圍為 [0% ~ 100%];RELATIVE_TO_PARENT 則相對於父控件,如 "50%p" 表示中軸點位於父控件中間,取值範圍同為 [0% ~ 100%]。

效果如下:


RotateAnimation – 旋轉動畫

XML 屬性名稱描述 android:fromDegrees 動畫起始角度(可正可負) android:toDegrees 動畫終止角度(可正可負) android:pivotX 旋轉作用點在 X 軸方向的位置 android:pivotY 旋轉作用點在 Y 軸方向的位置
XML 中設置旋轉動畫
 
代碼中設置旋轉動畫
 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 平移動畫起始位置 X 軸坐標 android:toXDelta 平移動畫結束位置 X 軸坐標 android:fromYDelta 平移動畫起始位置 Y 軸坐標 android:toYDelta 平移動畫結束位置 Y 軸坐標
代碼中設置平移動畫
 TranslateAnimation translateAnimation = new TranslateAnimation(0, 200, 0, 0);
translateAnimation.setDuration(1000);
translateAnimation.setInterpolator(new AnticipateOvershootInterpolator());
targetIv.startAnimation(translateAnimation);


AlphaAnimation – 漸變動畫

XML 屬性名稱描述 android:fromAlpha 動畫開始時操作對象的 alpha 值 android:toAlpha 動畫終止時操作對象的 alpha 值
代碼中設置漸變動畫
 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 – 動畫集合

前面介紹的都是單獨的動畫,我們可以將多個動畫組合到一起形成一個集合。動畫集合同樣可以在 XML 中設置,用 set 標簽包含其他子動畫。相比公共動畫屬性,它多了一個 android:shareInterpolator="boolean",用於表示是否讓子動畫共用相同的插值器。

XML 中設置 set 動畫集合
 
    
        
    

我們來看一個現象:設置好上面的 set 動畫後,運行時會發現動畫開始時會先變小、旋轉一個角度,然後才正式開始。仔細分析 XML 代碼後發現,動畫開始時把 scale 和 rotate 的初始狀態應用了起來,這時想到了 android:fillBefore 屬性。但即使在 scale、rotate 動畫裡添加了 android:fillBefore="false" 後仍然無效。查看 Animation 類源碼才發現,fillBefore 必須在 fillEnabled="true" 時才生效,而 fillBefore 的默認值為 true,所以才會出現上述情況。

再次修改後,代碼如下:

 
    
        
    

效果如下:


Frame 幀動畫

Frame 動畫就是把圖片一幀一幀地播放出來,效果類似 GIF 圖片。幀動畫的設置很簡單,只需按順序把每一幀對應的圖片添加進去,設置好每幀的顯示時長,然後為 View 控件設置該動畫並播放即可。

XML 設置幀動畫
 
    
    
    
    
    
    
    

給 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 中的每個子 View 按照一定規則依次展示動畫。例如可以為 ListView、GridView 或 RecyclerView 定義 item 的進場動畫,而不是生硬地一次性全部顯示出來。

一般對 ListView 使用 layoutAnimation 動畫,對 GridView 使用 gridLayoutAnimation 動畫。對 RecyclerView 來說,通常只能使用 layoutAnimation 動畫,直接應用 gridLayoutAnimation 動畫會報錯,但可以通過自定義 RecyclerView 子類進行處理以支援 gridLayoutAnimation。

XML 屬性對應方法描述 android:delay setDelay(float) 動畫播放的延遲時間 android:animationOrder setOrder(int) 子 View 播放動畫的順序 android:interpolator setInterpolator(Interpolator) 插值器 android:animation LayoutAnimationController(animation) 指定子 View 的動畫
XML 定義 LayoutAnimation
 
代碼中定義 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 的動畫
代碼中設置

同樣是使用一個 Animation 構造出 GridLayoutAnimation 對象,設置各項參數後,最後將此動畫設置給 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 擴展

通常情況下,我們可以對 RecyclerView 使用 LayoutAnimation 動畫。但如果對 RecyclerView 使用動畫時出現以下錯誤:

 AndroidRuntime: FATAL EXCEPTION: main
Process: com.jacksen.demo.view, PID: 30770
java.lang.ClassCastException: android.view.animation.LayoutAnimationController$AnimationParameters cannot be cast to android.view.animation.GridLayoutAnimationController$AnimationParameters
    at android.view.animation.GridLayoutAnimationController.getDelayForView(GridLayoutAnimationController.java:299)
    at android.view.animation.LayoutAnimationController.getAnimationForView(LayoutAnimationController.java:321)
    at android.view.ViewGroup.bindLayoutAnimation(ViewGroup.java:3717)
    at android.view.ViewGroup.dispatchDraw(ViewGroup.java:2892)

錯誤含義是 GridLayoutAnimationController.AnimationParameters 無法強轉為 LayoutAnimationController.AnimationParameters。

RecyclerView 的出現本來就是為了替代 ListView,同時它也能呈現出 GridView 的效果。那麼,該如何讓設置了 GridLayoutManager 的 RecyclerView 應用 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;
    ...
}

隨後我們去 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 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 時,不能設置 stackFromEnd 屬性:

 /** stackFromEnd is not supported by GridLayoutManager. Consider using 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