編輯:Android 資訊
春節假期剛到,就趕緊擠出點時間寫點技術文章,這篇已經醞釀很久了。我們經常能看到很多擁有酷炫動畫的 App,給人一種高逼格的氣息。自從 Google 更新 Android 5.0 以來,Android 世界變得異常豐富多彩。本篇主要講解 Android 5.0/6.0 之後實現酷炫動畫的新技術,包括靜態與動態的 VectorDrawable、軌跡動畫、路徑變換動畫,並指出目前常見的一些兼容性問題,堪稱滿滿的干貨。
在學習矢量圖動畫之前,我們需要先回顧一下屬性動畫的知識點,因為動態矢量圖動畫是需要結合屬性動畫來實現的。
使用動態的 VectorDrawable 需要結合屬性動畫來實現,所以下面先回顧一下屬性動畫。Android 3.0 引入了全新的屬性動畫系統,這個新系統讓「為任意對象的任意類型屬性製作動畫」變得輕而易舉,包括 Android 3.0 中加入 View 的那些新屬性。到了 Android 3.1,又新增了一些工具類,使得為 View 對象製作屬性動畫更加容易。
傳統動畫(Animation)是透過系統不斷呼叫 onDraw 方法重繪界面來實現動畫效果,不適合做交互動畫,只適用於顯示動畫;而屬性動畫(Animator)則是透過操作一個屬性的 get、set 方法,去真實地改變這個屬性。這裡我們只針對屬性動畫(Animator)進行說明。
注意:屬性動畫在 Google 提供的 APIDemo 中已有大量案例,建議多加揣摩學習。
屬性動畫中最簡單、最常用的就是 ObjectAnimator:
1)作用于單個屬性的動畫實現:
/** * 參數1: 操縱的控件 * 參數2: 操縱的屬性, 常見的有偏移translationX、translationY, 絕對值x、y, 3D旋轉rotation、 * 水平\豎直方向旋轉rotationX\rotationY, 水平\豎直方向縮放scaleX\scaleX,透明度alpha * 參數3,4: 變化范圍 * setDuration: 設置顯示時長 */ ObjectAnimator.ofFloat(imageView, "translationX", 0F, 200F).setDuration(1000).start();

同樣,屬性動畫也可以在 res/animator 文件夾下創建 anim.xml 並配置(多個 objectAnimator 可以用 set 進行包裹):
<?xml version="1.0" encoding="utf-8"?> <objectAnimator xmlns:androd="https://schemas.android.com/apk/res/android" androd:duration="1000" androd:propertyName="translationX" androd:valueFrom="0F" androd:valueTo="200F" androd:valueType="floatType"> </objectAnimator>
這段 XML 實現的效果,和我們剛才用代碼實現的動畫一模一樣,每個參數的含義都非常清楚,相信大家都是一看就懂,我就不再一一解釋了。
XML 文件編寫好之後,我們如何在代碼中把文件加載進來並啟動動畫呢?只需調用如下代碼即可:
Animator animator = AnimatorInflater.loadAnimator(context, R.animator.anim); animator.setTarget(view); animator.start();
調用 AnimatorInflater 的 loadAnimator 把 XML 動畫文件加載進來,再調用 setTarget() 方法把這個動畫設置到某個對象上,最後調用 start() 方法啟動動畫,就這麼簡單。
2)同時作用于多個屬性的動畫實現:
所有動畫同時播放:
ObjectAnimator animator1 = ObjectAnimator.ofFloat(imageView, "translationX", 0F, 200F); ObjectAnimator animator2 = ObjectAnimator.ofFloat(imageView, "translationY", 0F, 200F); AnimatorSet set = new AnimatorSet(); set.playTogether(animator1, animator2); set.setDuration(1000).start();

所有動畫按順序播放:
ObjectAnimator animator1 = ObjectAnimator.ofFloat(imageView, "translationX", 0F, 200F); ObjectAnimator animator2 = ObjectAnimator.ofFloat(imageView, "translationY", 0F, 200F); AnimatorSet set = new AnimatorSet(); set.playSequentially(animator1, animator2); set.setDuration(1000).start();

有的同時播放、有的按順序:
ObjectAnimator animator1 = ObjectAnimator.ofFloat(imageView, "translationX", 0F, 200F); ObjectAnimator animator2 = ObjectAnimator.ofFloat(imageView, "translationY", 0F, 200F); ObjectAnimator animator3 = ObjectAnimator.ofFloat(imageView, "rotation", 0F, 360F); AnimatorSet set = new AnimatorSet(); set.play(animator1).with(animator2);//同時 set.play(animator3).after(animator1);//之後, 另外還有before之前 set.setDuration(1000).start();

3)屬性動畫的結束監聽事件
animator.addListener(new AnimatorListenerAdapter() { @Override public void onAnimationEnd(Animator animation) { super.onAnimationEnd(animation); } });
ValueAnimator 不會作用于任何一個屬性,簡單來說,它就是一個「數值發生器」。實際上,屬性動畫中每一步具體的動畫效果,都是透過 ValueAnimator 計算出來的。ObjectAnimator 是繼承自 ValueAnimator 的,而 ValueAnimator 的使用並沒有 ObjectAnimator 那麼廣泛。ValueAnimator 透過動畫已經進行的時間與總時間的比值,產生一個 0~1 的時間因子,有了這樣的時間因子,經過相應的變換,就能根據 startValue 和 endValue 生成中間對應的值。
1)顯示 ValueAnimator 生成的數值(這裡沒有指定插值器,默認線性增長):
ValueAnimator animator = ValueAnimator.ofInt(0, 100); animator.setDuration(5000); animator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() { @Override public void onAnimationUpdate(ValueAnimator valueAnimator) { Integer value = (Integer) valueAnimator.getAnimatedValue(); textView.setText(""+value); } }); animator.start();

2)自定義數值生成器
ValueAnimator animator = ValueAnimator.ofObject(new TypeEvaluator() { /** * 通過重寫evaluate方法返回各種各樣的值 * @param fraction 時間因子 0到1之間變化到數值 * @param startValue * @param endValue * @return */ @Override public Object evaluate(float fraction, Object startValue, Object endValue) { return null; } });
ValueAnimator\ObjectAnimator AnimatorUpdateListener\AnimatorListenerAdapter 做監聽器的 PropertyValuesHolder\AnimatorSet 控制動態集合的顯示效果、順序、流程的 TypeEvaluators 值計算器 Interpolators 插值器
Interpolator 圖示:

這些常用的方法/類,官方 API 都有詳細說明,建議多閱讀官方 API 文檔:https://developer.android.google.cn/reference/android/animation/package-summary.html
下面正式開始矢量圖動畫的開發。
VectorDrawable,即矢量圖動畫,使用時需要添加兼容庫,在 app 的 build.gradle 文件相關節點下添加:
android { defaultConfig { vectorDrawables.useSupportLibrary = true } } dependencies { compile 'com.android.support:appcompat-v7:25.1.0'//23.2及以上 }
SVG 是一套語法規範,用於前端;而 Vector 只實現了 SVG 語法的 Path 標簽(為了提高解析效率),用於 Android。Vector 的語法透過字母和數字的組合來描述一個路徑,不同字母代表不同含義,例如:
M = moveto(M X,Y): 將畫筆移動到指定的坐標位置 L = lineto(L X,Y): 畫直線到指定的坐標位置 Z = closepath(): 關閉路徑
Vector 還提供一些封裝好的方法:
H = horizontal lineto(H X): 畫水平線到指定的X坐標位置 V = vertical lineto(V Y): 畫垂直線到指定的Y坐標位置
例如下面這個 Vector Asset 代表一個黑色的正方形:
<vector xmlns:android="https://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportWidth="24.0" android:viewportHeight="24.0"> <path android:name="square" android:fillColor="#FF000000" android:pathData="M10,10 L20,10 L20,20 L10,20 z"/> </vector>
解釋:
1)如上,依次以 M10,10 -> L20,10 -> L20,20 -> L10,20 -> z 進行繪制;
2)width/height 代表 vector 的大小;viewportWidth/viewportHeight 則代表把 vector 均勻分為 24 整份,pathData 就按照這裡的標準來繪制。
在 ImageView、ImageButton 這類控件中使用非常簡單:
<!-- 注意:這裡用的是srcCompat --> app:srcCompat="@drawable/vector_image"
如果要在 Button 這種帶點擊效果的控件中使用,則需要透過 selector 來設置,並在對應 Activity 中開啟下面的設置:
static { AppCompatDelegate.setCompatVectorFromResourcesEnabled(true); }
這裡需要結合屬性動畫來實現動態的 VectorDrawable 效果:
1)創建 VectorDrawable 文件 arrow.xml
<vector xmlns:android="https://schemas.android.com/apk/res/android" android:width="24dp" android:height="24dp" android:viewportHeight="24.0" android:viewportWidth="24.0"> <group android:name="left"> <path android:fillColor="#FF000000" android:pathData="M6,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z"/> </group> <group android:name="right"> <path android:fillColor="#FF000000" android:pathData="M18,10c-1.1,0 -2,0.9 -2,2s0.9,2 2,2 2,-0.9 2,-2 -0.9,-2 -2,-2z"/> </group> </vector>
Android Studio 的 Preview 窗口顯示效果如下:

2)為 VectorDrawable 創建屬性動畫:
左邊小球的屬性動畫 anim_left.xml 如下:
<?xml version="1.0" encoding="utf-8"?> <objectAnimator xmlns:androd="https://schemas.android.com/apk/res/android" androd:duration="1000" androd:interpolator="@android:interpolator/overshoot" androd:propertyName="translateX" androd:repeatCount="infinite" androd:repeatMode="reverse" androd:valueFrom="0" androd:valueTo="10" androd:valueType="floatType"> </objectAnimator> <!-- duration="1000" 持續時間/毫秒 interpolator 修飾動畫效果,定義動畫的變化率(加速,減速,重復,彈跳) propertyName="translateX"屬性名(還有前面回顧屬性動畫提到的屬性,另外還有顏色漸變fillColor/軌跡繪制trimPathStart) repeatCount="infinite" 無限次 repeatMode="reverse" 重復模式:循環使用 valueFrom="0" 起始值 valueTo="10" 結束值 valueType="floatType" 變化值的類型:浮點型變化 -->
右邊小球的屬性動畫 anim_right.xml 如下:
<?xml version="1.0" encoding="utf-8"?> <objectAnimator xmlns:androd="https://schemas.android.com/apk/res/android" androd:duration="1000" androd:interpolator="@android:interpolator/overshoot" androd:propertyName="translateX" androd:repeatCount="infinite" androd:repeatMode="reverse" androd:valueFrom="0" androd:valueTo="-10" androd:valueType="floatType"> </objectAnimator>
3)接下來我們需要配置動畫粘合劑 animated-vector(arrow_anim.xml),讓屬性動畫作用于 VectorDrawable:
<?xml version="1.0" encoding="utf-8"?> <animated-vector xmlns:android="https://schemas.android.com/apk/res/android" android:drawable="@drawable/arrow"> <target android:animation="@animator/anim_left" android:name="left"/> <target android:animation="@animator/anim_right" android:name="right"/> </animated-vector>
4)粘合到一起之後,我們就可以在 Activity 的 Layout 文件中引用了:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="match_parent" android:layout_height="45dp" app:srcCompat="@drawable/arrow_anim" android:onClick="anim"/> </RelativeLayout>
5)在 Activity 中添加點擊事件 anim:
public void anim(View view) { ImageView imageView = (ImageView) view; Drawable drawable = imageView.getDrawable(); if (drawable instanceof Animatable) { ((Animatable) drawable).start(); } }
到此,動態的 VectorDrawable 就編寫完畢了。我們運行程序,點擊 ImageView,出現了如下的效果:

是不是很不錯。
軌跡動畫關鍵的配置,就是 objectAnimator 中的 androd:propertyName=”trimPathStart” 屬性。
1)創建 VectorDrawable 文件 path.xml
<vector xmlns:android="https://schemas.android.com/apk/res/android" android:width="200dp" android:height="200dp" android:viewportHeight="500" android:viewportWidth="500"> <group android:scaleX="5.0" android:scaleY="5.0"> <path android:name="start" android:pathData="M 50.0,90.0 L 82.9193546357,27.2774101308 L 12.5993502926,35.8158045183 L 59.5726265715,88.837672697 L 76.5249063296,20.0595700732 L 10.2916450361,45.1785327898 L 68.5889268818,85.4182410261 L 68.5889268818,14.5817589739 L 10.2916450361,54.8214672102 L 76.5249063296,79.9404299268 L 59.5726265715,11.162327303 L 12.5993502926,64.1841954817 L 82.9193546357,72.7225898692 L 50.0,10.0 L 17.0806453643,72.7225898692 L 87.4006497074,64.1841954817 L 40.4273734285,11.162327303 L 23.4750936704,79.9404299268 L 89.7083549639,54.8214672102 L 31.4110731182,14.5817589739 L 31.4110731182,85.4182410261 L 89.7083549639,45.1785327898 L 23.4750936704,20.0595700732 L 40.4273734285,88.837672697 L 87.4006497074,35.8158045183 L 17.0806453643,27.2774101308 L 50.0,90.0Z" android:strokeColor="#000000" android:strokeWidth="2"/> </group> </vector>
Android Studio 的 Preview 窗口顯示效果如下:

2)為 VectorDrawable 創建屬性動畫:
屬性動畫 anim_path.xml 如下:
<?xml version="1.0" encoding="utf-8"?> <set xmlns:androd="https://schemas.android.com/apk/res/android"> <objectAnimator androd:duration="10000" androd:propertyName="trimPathStart" androd:repeatCount="infinite" androd:repeatMode="reverse" androd:valueFrom="1" androd:valueTo="0" androd:valueType="floatType"> </objectAnimator> <objectAnimator androd:duration="10000" androd:propertyName="strokeColor" androd:repeatCount="infinite" androd:repeatMode="reverse" androd:valueFrom="@android:color/holo_red_dark" androd:valueTo="@android:color/holo_blue_dark" androd:valueType="colorType"> </objectAnimator> </set>
3)接下來我們需要配置動畫粘合劑 animated-vector(path_anim.xml),讓屬性動畫作用于 VectorDrawable:
<?xml version="1.0" encoding="utf-8"?> <animated-vector xmlns:android="https://schemas.android.com/apk/res/android" android:drawable="@drawable/path"> <target android:animation="@animator/anim_path" android:name="start"/> </animated-vector>
4)粘合到一起之後,我們就可以在 Activity 的 Layout 文件中引用了:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="match_parent" android:layout_height="100dp" app:srcCompat="@drawable/path_anim" android:onClick="anim"/> </RelativeLayout>
5)在 Activity 中添加點擊事件 anim:
public void anim(View view) { ImageView imageView = (ImageView) view; Drawable drawable = imageView.getDrawable(); if (drawable instanceof Animatable) { ((Animatable) drawable).start(); } }
到此,軌跡動畫就編寫完畢了。我們運行程序,點擊 ImageView,出現了如下的效果:

路徑變換動畫關鍵的配置,就是 objectAnimator 中的 androd:propertyName=”pathData” 和 androd:valueType=”pathType” 屬性。這裡我們實現五角星向五邊形的變換動畫。
1)創建五角星 VectorDrawable 文件 fivestar.xml
<vector xmlns:android="https://schemas.android.com/apk/res/android" android:width="120dp" android:height="120dp" android:viewportHeight="64" android:viewportWidth="64"> <group> <path android:name="star" android:fillColor="#22e171" android:pathData="M 48,54 L 31,42 15,54 21,35 6,23 25,23 32,4 40,23 58,23 42,35 z" android:strokeColor="#000000" android:strokeWidth="1"/> </group> </vector>
Android Studio 的 Preview 窗口顯示效果如下:

2)為 VectorDrawable 創建屬性動畫:
五角星的屬性動畫 anim_fivestar.xml 如下:
<?xml version="1.0" encoding="utf-8"?> <objectAnimator xmlns:androd="https://schemas.android.com/apk/res/android" androd:duration="3000" androd:propertyName="pathData" androd:valueFrom="M 48,54 L 31,42 15,54 21,35 6,23 25,23 32,4 40,23 58,23 42,35 z" androd:valueTo="M 48,54 L 31,54 15,54 10,35 6,23 25,10 32,4 40,10 58,23 54,35 z" androd:valueType="pathType"> </objectAnimator>
3)接下來我們需要配置動畫粘合劑 animated-vector(fivestar_anim.xml),讓屬性動畫作用于 VectorDrawable:
<?xml version="1.0" encoding="utf-8"?> <animated-vector xmlns:android="https://schemas.android.com/apk/res/android" android:drawable="@drawable/fivestar"> <target android:animation="@animator/anim_fivestar" android:name="star"/> </animated-vector>
4)粘合到一起之後,我們就可以在 Activity 的 Layout 文件中引用了:
<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android" xmlns:app="https://schemas.android.com/apk/res-auto" android:id="@+id/activity_main" android:layout_width="match_parent" android:layout_height="match_parent"> <ImageView android:layout_width="match_parent" android:layout_height="100dp" app:srcCompat="@drawable/fivestar_anim" android:onClick="animL"/> </RelativeLayout>
5)在 Activity 中添加點擊事件 anim:
/** * 指該方法適用Android版本大於等於Android L * @param view */ @TargetApi(Build.VERSION_CODES.LOLLIPOP) public void animL(View view) { ImageView imageView = (ImageView) view; AnimatedVectorDrawable drawable = (AnimatedVectorDrawable) getDrawable(R.drawable.fivestar_anim); imageView.setImageDrawable(drawable); if (drawable != null) { drawable.start(); } }
這裡的點擊事件和前面介紹過的略有不同,需要考慮到 VectorDrawable 實現路徑變換動畫的兼容性問題,因此路徑變換動畫目前存在兼容性問題,無法在 4.X 版本運行,這一點要格外注意。不過我們同樣希望 Google 能在後續版本中優化路徑變換動畫,提高兼容性。
到此,路徑變換動畫就編寫完畢了。我們運行程序,點擊 ImageView,出現了如下的效果:

1)路徑變換動畫(Path Morphing)
在 Android pre-L 版本下無法使用,例如把圓形變換成三角形的動畫。
2)路徑插值器(Path Interpolation)
在 Android pre-L 版本只能使用系統的插值器(一般情況下,系統提供的 27 種插值器已經足夠我們使用了),不能自定義。
1)路徑變換動畫(Path Morphing)
在 Android L 版本以上需要使用代碼配置。
不支持從 String.xml 中讀取
<PathData>
同時,也希望 Google 能在後面的版本中修復這些動態 VectorDrawable 的兼容性問題。
Android HashMap 原始碼解析
HashMap 的結構 HashMap 以陣列加鏈表儲存資料。每個桶位保存 HashMapEntry,每個 entry 包含 key、value、hash 與 next。
Android開發者必備的50個技巧、快捷鍵與資源
本文旨在整理Android Studio實用的提示、技巧、快捷鍵與參考資源,幫助你提升整體效率與操作表現。以下以MacOS X上的Android Studio為例,與Wi
Android 黑白棋實現:規則、極小極大演算法與棋力評估
黑白棋又稱蘋果棋,規則簡單但變化豐富。玩家透過翻轉對方棋子來擴張版圖,最後以棋盤上的棋子數量決定勝負。本文以一個 Android 黑白棋專案為例,說明遊戲規則、AI 演算
Android UI 控件系列:TableLayout 表格布局教學
TableLayout 是 Android 中常見的表格容器,主要用來以列和行的方式排列子檢視。它很適合用來製作選單、表單、對齊清單等需要整齊排列的畫面。建立範例專案新增