編輯:關於 Android 程式設計
動畫在實際開發中佔有很重要的地位。一個優秀的動畫能為 App 增色不少,好的動畫銜接更能強化身體邏輯的呈現。Android 提供了幾種動畫方案:Frame Animation(幀動畫)、Tween Animation(補間動畫),以及 3.0 之後加入的 Property Animator(屬性動畫)。熟練運用這些工具,才能做出恰到好處的效果。
幀動畫顧名思義,效果是由一幀幀圖片串接而成:透過指定圖片的播放順序,達到動畫效果。Android 提供了 animation-list 節點專門用來配置幀動畫。
1. 建立 animation 資料夾,用來存放 XML 動畫檔(res/anim 或 res/drawable 皆可)。

2. 撰寫動畫配置:在 animation-list 節點下逐一列出 item。
3. 設定到 ImageView 背景並播放:把背景轉型為 AnimationDrawable 後呼叫 start()。
iv_imageView.setBackgroundResource(R.drawable.frame_animation); AnimationDrawable animation = (AnimationDrawable) iv_imageView.getBackground(); animation.start();

這種效果用 Frame Animation 就能完成:把 GIF 逐幀切成一張張圖片,再在 animation-list 中指定播放順序即可。
<animation-list xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/Horse_start" android:duration="200" />
<item android:drawable="@mipmap/Horse1" android:duration="200" />
<item android:drawable="@mipmap/Horse2" android:duration="200" />
<item android:drawable="@mipmap/Horse3" android:duration="200" />
<item android:drawable="@mipmap/Horse4" android:duration="200" />
<item android:drawable="@mipmap/Horse5" android:duration="200" />
<item android:drawable="@mipmap/Horse6" android:duration="200" />
<item android:drawable="@mipmap/Horse7" android:duration="200" />
<item android:drawable="@mipmap/Horse8" android:duration="200" />
<item android:drawable="@mipmap/Horse_start" android:duration="200" />
</animation-list>
item 的先后顺序就是播放順序。接著把它綁到 ImageView 上:
<ImageView
android:id="@+id/iv_frame"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
android:background="@anim/run_horse" />
ImageView iv_animaView = (ImageView) findViewById(R.id.iv_frame); AnimationDrawable animationDrawable = (AnimationDrawable) iv_animaView.getBackground(); animationDrawable.start();
效果:

幾行程式碼就做出 GIF 般的動畫,門檻確實很低。目前也有不錯的開源庫能直接載入 GIF,效能差異值得實測比較。

<animation-list xmlns:android="https://schemas.android.com/apk/res/android">
<item android:drawable="@mipmap/zzlx1" android:duration="200" />
<item android:drawable="@mipmap/zzlx2" android:duration="200" />
<item android:drawable="@mipmap/zzlx3" android:duration="200" />
<item android:drawable="@mipmap/zzlx4" android:duration="200" />
<item android:drawable="@mipmap/zzlx5" android:duration="200" />
<item android:drawable="@mipmap/zzlx6" android:duration="200" />
<item android:drawable="@mipmap/zzlx7" android:duration="200" />
<item android:drawable="@mipmap/zzlx8" android:duration="200" />
</animation-list>
後續程式碼同上。

前面的做法是:把背景對應的 Drawable 轉型成 AnimationDrawable,再由它啟動動畫。這個類別究竟是什麼?一起來看。
AnimationDrawable 用於建立 frame-by-frame(逐幀)動畫,它定義了一系列 Drawable 物件,可設定為 View 的背景。最簡單的方式是透過 XML 建立,放到 res/drawable 下,再設為 view 的 background。XML 結構:
animation-list:根節點,包含一系列 itemitem:每個 item 對應一幀在程式碼中建立與使用:
ImageView img = (ImageView) findViewById(R.id.spinning_wheel_image); img.setBackgroundResource(R.drawable.spin_animation); AnimationDrawable frameAnimation = (AnimationDrawable) img.getBackground(); frameAnimation.start();
可用屬性:
AnimationDrawable_visible:是否可見AnimationDrawable_variablePadding:變數內距AnimationDrawable_oneshot:是否只播放一次(true 是,false 否)AnimationDrawableItem_duration:每幀之間的時間間隔AnimationDrawableItem_drawable:每幀對應的 drawable我們心中有幾個疑問:AnimationDrawable 如何形成一幀幀畫面?如何循環播放?能否用程式碼控制播放?

XML 如何變成 Drawable?關鍵在 Drawable.createFromXml():
/**
* Create a drawable from an XML document.
*/
public static Drawable createFromXml(Resources r, XmlPullParser parser)
throws XmlPullParserException, IOException {
return createFromXml(r, parser, null);
}
public static Drawable createFromXml(Resources r, XmlPullParser parser, Theme theme)
throws XmlPullParserException, IOException {
AttributeSet attrs = Xml.asAttributeSet(parser);
int type;
while ((type = parser.next()) != XmlPullParser.START_TAG
&& type != XmlPullParser.END_DOCUMENT) {
// 空迴圈,往後找起始標籤
}
if (type != XmlPullParser.START_TAG) {
throw new XmlPullParserException("No start tag found");
}
Drawable drawable = createFromXmlInner(r, parser, attrs, theme);
if (drawable == null) {
throw new RuntimeException("Unknown initial tag: " + parser.getName());
}
return drawable;
}
Android 內部同樣用 XmlPullParser 解析 XML,先定位起始與結束標籤,再交由 createFromXmlInner() 解析並產生 Drawable 物件。
public static Drawable createFromXmlInner(Resources r, XmlPullParser parser,
AttributeSet attrs, Theme theme) throws XmlPullParserException, IOException {
final Drawable drawable;
final String name = parser.getName();
switch (name) {
case "selector": drawable = new StateListDrawable(); break;
case "animated-selector": drawable = new AnimatedStateListDrawable(); break;
case "level-list": drawable = new LevelListDrawable(); break;
case "layer-list": drawable = new LayerDrawable(); break;
case "transition": drawable = new TransitionDrawable(); break;
case "ripple": drawable = new RippleDrawable(); break;
case "color": drawable = new ColorDrawable(); break;
case "shape": drawable = new GradientDrawable(); break;
case "vector": drawable = new VectorDrawable(); break;
case "animated-vector": drawable = new AnimatedVectorDrawable(); break;
case "scale": drawable = new ScaleDrawable(); break;
case "clip": drawable = new ClipDrawable(); break;
case "rotate": drawable = new RotateDrawable(); break;
case "animated-rotate": drawable = new AnimatedRotateDrawable(); break;
case "animation-list": drawable = new AnimationDrawable(); break; // ← 我們的case
case "inset": drawable = new InsetDrawable(); break;
case "bitmap": drawable = new BitmapDrawable(); break;
case "nine-patch": drawable = new NinePatchDrawable(); break;
default:
throw new XmlPullParserException(parser.getPositionDescription()
+ ": invalid drawable tag " + name);
}
drawable.inflate(r, parser, attrs, theme);
return drawable;
}
程式碼先讀取標籤名稱,據此建立對應的 Drawable;由於 AnimationDrawable 已覆寫 inflate(),接著走的是:
@Override
public void inflate(Resources r, XmlPullParser parser, AttributeSet attrs, Theme theme)
throws XmlPullParserException, IOException {
final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.AnimationDrawable);
super.inflateWithAttributes(r, parser, a, R.styleable.AnimationDrawable_visible);
updateStateFromTypedArray(a);
a.recycle();
inflateChildElements(r, parser, attrs, theme);
setFrame(0, true, false);
}
一幀幀畫面從哪來?先認識 AnimationState:
private final static class AnimationState extends DrawableContainerState
它繼承 DrawableContainerState,而後者有一個成員 Drawable[] mDrawables,正是用來存放我們的每一幀。理解這點後,再看 inflateChildElements():
private void inflateChildElements(Resources r, XmlPullParser parser,
AttributeSet attrs, Theme theme) throws XmlPullParserException, IOException {
int type;
final int innerDepth = parser.getDepth() + 1;
int depth;
while ((type = parser.next()) != XmlPullParser.END_DOCUMENT
&& ((depth = parser.getDepth()) >= innerDepth || type != XmlPullParser.END_TAG)) {
if (type != XmlPullParser.START_TAG) {
continue;
}
if (depth > innerDepth || !parser.getName().equals("item")) {
continue;
}
final TypedArray a = obtainAttributes(r, theme, attrs, R.styleable.AnimationDrawableItem);
final int duration = a.getInt(R.styleable.AnimationDrawableItem_duration, -1);
if (duration < 0) {
throw new XmlPullParserException(parser.getPositionDescription()
+ ": <item> tag requires a 'duration' attribute");
}
Drawable dr = a.getDrawable(R.styleable.AnimationDrawableItem_drawable);
a.recycle();
if (dr == null) {
while ((type = parser.next()) == XmlPullParser.TEXT) {
// 空迴圈
}
if (type != XmlPullParser.START_TAG) {
throw new XmlPullParserException(parser.getPositionDescription()
+ ": <item> tag requires a 'drawable' attribute or child tag defining a drawable");
}
dr = Drawable.createFromXmlInner(r, parser, attrs, theme);
}
mAnimationState.addFrame(dr, duration); // ← 一幀幀存進陣列
if (dr != null) {
dr.setCallback(this);
}
}
}
這裡透過 TypedArray 取出每個 item 的 drawable 與 duration,再呼叫 addFrame() 把動畫資訊存進 Drawable 陣列。
動畫怎麼啟動?
public void start() {
mAnimating = true;
if (!isRunning()) {
// 從第 0 幀開始;若非單次播放則同時開啟循環
setFrame(0, false, mAnimationState.getChildCount() > 1 || !mAnimationState.mOneShot);
}
}
接著由 setFrame() 內的 selectDrawable(frame) 完成實際的畫面切換。
後續會再整理另外幾篇動畫相關文章。
Android 錄音與音頻播放功能完整實現教程
本文記錄了一個錄製聲音文件並播放的完整 Demo 實現過程,供需要的朋友參考。 先說明幾點注意事項:其一,這個 Demo 未對「多次快速點擊同一個音頻文件」做完善處理,偶
Android 自定義陰影效果:LayerDrawable 遮罩原理與實作
Android 5.x 之後,Google 加入了 android:elevation 與 android:translationZ 兩個屬性,對應垂直方向上的高度變化,
OkHttp 框架入門實戰:Android 網路請求一篇搞定
自 Android 6.0 起,Google 移除了 HttpClient 相關 API,改用 HttpURLConnection 取代。在實際開發中,網路請求幾乎是每個
Xposed 框架實戰:Hook 定位 API 以模擬 GPS 位置(測試用途)
本文說明如何利用 Xposed 框架攔截系統的定位相關 API,讓 App 取得一個自訂的假位置。這個能力在開發與測試上很實用——例如驗證「附近的人」功能、測試不同地區的