編輯:關於 Android 程式設計
動畫好不好看,往往不取決於「動了什麼」,而取決於「怎麼動」。同樣是一顆小球從上往下掉,先加速後減速和先做減速後加速,觀感天差地遠。控制這件事的關鍵,就是 Interpolator。
Interpolator 用來修飾動畫效果,本質上是定義「動畫的變化率」,讓同一段位移呈現出加速、減速、重複、彈跳等不同的節奏。它常被直譯為「補間器」。
Android 文件中的定義如下:

系統內建常用的幾種:
· AccelerateDecelerateInterpolator:頭尾慢、中段快,是屬性動畫的預設值;
· AccelerateInterpolator:起步慢,之後逐漸加速;
· DecelerateInterpolator:起步快,之後逐漸減速;
· AnticipateInterpolator:先向後退一小段,再往前衝;
· AnticipateOvershootInterpolator:先向後退,再往前衝過頭,最後回到終點;
· OvershootInterpolator:往前衝過頭,再退回原定位置;
· BounceInterpolator:結束時像皮球一樣反覆彈跳;
· CycleInterpolator:以正弦曲線的節奏重複指定次數;
· LinearInterpolator:等速變化。
如果內建的都不合用,也可以自己寫一個。
Interpolator 並不是屬性動畫才有的新東西,從 Android 1.0 起它就存在,早期的補間動畫也支援。屬性動畫新增的是 TimeInterpolator 介面,它的設計目的是向下相容——所有舊的 Interpolator 實作都能直接拿來用在屬性動畫上。

也就是說,TimeInterpolator 已經有一大票現成實作可用,每種都有各自的節奏。AccelerateInterpolator 是加速,DecelerateInterpolator 是減速,以此類推。
回頭看前面學過的屬性動畫,其實沒有一次是等速的。用 ValueAnimator 打印出來的數值就是證據:

開頭以 0.0 起頭的值連續出現四次,變化很慢,之後明顯加速,尾段又慢了下來——這正是先加速後減速的特徵。
再看小球移動變色的例子:

小球一開始移動緩慢,然後逐漸加速,中段最快,之後減速、緩緩停住;顏色的變化節奏也完全一致。
結論很明確:屬性動畫預設的 Interpolator 就是先加速後減速,對應的實作類是 AccelerateDecelerateInterpolator。而替換它,只需要一行 setInterpolator()。
沿用小球範例,這裡把 Point 的座標改成垂直落下,模擬自由落體:
private void startAnimation() {
Point startPoint = new Point(getWidth() / 2, RADIUS);
Point endPoint = new Point(getWidth() / 2, getHeight() - RADIUS);
ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
currentPoint = (Point) animation.getAnimatedValue();
invalidate();
}
});
anim.setDuration(2000);
anim.start();
}
此時小球從螢幕正中央頂部落到底部,但預設的先加速後減速不符合物理直覺——自由落體應該越掉越快。改成 AccelerateInterpolator 即可,它的建構方法還能帶一個 float 參數控制加速度大小:
private void startAnimation() {
Point startPoint = new Point(getWidth() / 2, RADIUS);
Point endPoint = new Point(getWidth() / 2, getHeight() - RADIUS);
ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
currentPoint = (Point) animation.getAnimatedValue();
invalidate();
}
});
anim.setInterpolator(new AccelerateInterpolator(2f));
anim.setDuration(2500);
anim.start();
}
效果立竿見影,預設的 Interpolator 已經被成功換掉:

不過畫面看起來還是有點怪:小球落地就靜止了。真實世界裡它應該反彈、再落下、再反彈,最後才停住。這套邏輯自己寫有點繁瑣,好在系統已經準備好了 BounceInterpolator:
private void startAnimation() {
Point startPoint = new Point(getWidth() / 2, RADIUS);
Point endPoint = new Point(getWidth() / 2, getHeight() - RADIUS);
ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
currentPoint = (Point) animation.getAnimatedValue();
invalidate();
}
});
anim.setInterpolator(new BounceInterpolator());
anim.setDuration(3000);
anim.start();
}
只換了一個 Interpolator,並把時間稍微加長(反覆彈跳本來就需要更多時間),效果就對了:

內建的這幾種只是代表,其他的建議自己跑一遍看節奏。
只會用內建的顯然不夠,我們來看它背後的機制。TimeInterpolator 的介面定義非常精簡:
/**
* A time interpolator defines the rate of change of an animation. This allows animations
* to have non-linear motion, such as acceleration and deceleration.
*/
public interface TimeInterpolator {
/**
* Maps a value representing the elapsed fraction of an animation to a value that represents
* the interpolated fraction. This interpolated value is then multiplied by the change in
* value of an animation to derive the animated value at the current elapsed animation time.
*
* @param input A value between 0 and 1.0 indicating our current point
* in the animation where 0 represents the start and 1.0 represents the end
* @return The interpolation value. This value can be more than 1.0 for
* interpolators which overshoot their targets, or less than 0 for
* interpolators that undershoot their targets.
*/
float getInterpolation(float input);
}
只有一個方法 getInterpolation()。傳入的 input 會隨動畫推進而不斷變化,規律很單純:依設定時長等速增加,範圍 0 到 1。動畫開始時是 0,結束時是 1。
那 input 和之前用過的 fraction 是什麼關係?簡單說,input 決定 fraction。input 由系統計算後傳進來,我們在 getInterpolation() 裡對它做運算,回傳值就是 fraction。
最單純的情況是原封不動把 input 傳回去,此時 fraction 等速增加,動畫就是等速。這正是 LinearInterpolator 的做法:
/**
* An interpolator where the rate of change is constant
*/
public class LinearInterpolator extends BaseInterpolator implements NativeInterpolatorFactory {
public LinearInterpolator() {
}
public LinearInterpolator(Context context, AttributeSet attrs) {
}
public float getInterpolation(float input) {
return input;
}
}
getInterpolation() 沒有任何邏輯,直接把 input 回傳,這就是等速動畫的全部秘密。
再看稍微複雜一點的 AccelerateDecelerateInterpolator:
/**
* An interpolator where the rate of change starts and ends slowly but
* accelerates through the middle.
*/
public class AccelerateDecelerateInterpolator implements Interpolator, NativeInterpolatorFactory {
public AccelerateDecelerateInterpolator() {
}
public AccelerateDecelerateInterpolator(Context context, AttributeSet attrs) {
}
public float getInterpolation(float input) {
return (float) (Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
}
}
程式碼長度沒多多少,但邏輯明顯複雜了。這裡主要用餘弦函數:input 範圍 0 到 1,走進 cos 之後角度範圍就是 π 到 2π。cos(π) 等於 -1,cos(2π) 等於 1,除以 2 再加 0.5,最終結果仍落在 0 到 1 之間。只是經過餘弦運算後,數值不再是等速增加,而是走過一段先加速後減速的過程。
把這個演算法畫成曲線會更直觀:

這是一條 S 型曲線:橫座標從 0 走到 0.2 時縱座標幾乎沒動,中段明顯加速,橫座標從 0.8 到 1 時又慢了下來。
自訂 Interpolator 的難點幾乎都在數學上。既然預設是先加速後減速,那我們就反過來做一個「先減速後加速」的版本,用正弦函數來實現。新建 DecelerateAccelerateInterpolator 並實作 TimeInterpolator:
public class DecelerateAccelerateInterpolator implements TimeInterpolator {
@Override
public float getInterpolation(float input) {
float result;
if (input <= 0.5) {
result = (float) (Math.sin(Math.PI * input)) / 2;
} else {
result = (float) (2 - Math.sin(Math.PI * input)) / 2;
}
return result;
}
}
原理是這樣:正弦函數在起始弧度附近的變化值很大,正好與餘弦相反,隨著弧度增加變化值逐漸變小,於是形成減速;當弧度超過 π/2 之後整個過程反轉,變化值又從小變大,直到弧度抵達 π 結束。0 到 π 這段路走完,就得到了先減速後加速的效果。
同樣畫成曲線:

依然是 S 型,但方向與前面相反:開頭縱座標變化幅度很大,然後逐漸收斂,橫座標到 0.5 時幾近於零,之後又重新放大。
換上去試試:
private void startAnimation() {
Point startPoint = new Point(getWidth() / 2, RADIUS);
Point endPoint = new Point(getWidth() / 2, getHeight() - RADIUS);
ValueAnimator anim = ValueAnimator.ofObject(new PointEvaluator(), startPoint, endPoint);
anim.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
currentPoint = (Point) animation.getAnimatedValue();
invalidate();
}
});
anim.setInterpolator(new DecelerateAccelerateInterpolator());
anim.setDuration(3000);
anim.start();
}
小球確實變成了先減速後加速,自訂 Interpolator 生效。

嚴格說 ViewPropertyAnimator 算不上什麼進階技巧,它甚至不是 3.0 就有的東西,而是在 3.1 才補上的功能——但因為太好用了,值得當作這一系列的回收尾。
屬性動畫的機制早已不是針對 View 設計的,它本質上是「不斷對數值做操作,再把值賦給某個物件的某個屬性」。可實務上,絕大多數時候我們操作的都是 View。Android 團隊意識到了這點,於是補了 ViewPropertyAnimator。
先看以前的寫法,例如把一個 TextView 變成透明:
ObjectAnimator animator = ObjectAnimator.ofFloat(textview, "alpha", 0f); animator.start();
不算複雜,但也不算好懂:要操作哪個 View、哪個屬性、變成什麼值,全都得塞進 ofFloat() 裡,不太符合我們平常寫物件導向的習慣。
換成 ViewPropertyAnimator:
textview.animate().alpha(0f);
清爽多了。animate() 是 3.1 新增的方法,它會回傳一個 ViewPropertyAnimator 物件,之後所有設定都透過它完成。
更棒的是它支援連綴,多個動畫可以輕ovember組合。例如讓 textview 移動到 (500, 500):
textview.animate().x(500).y(500);
設定時長同樣用連綴:
textview.animate().x(500).y(500).setDuration(5000);
前面學的 Interpolator 也能直接接上去:
textview.animate().x(500).y(500).setDuration(5000).setInterpolator(new BounceInterpolator());
有幾個細節值得注意:
整個機制建立在 View 新增的 animate() 方法上,它會建立並回傳 ViewPropertyAnimator 實例,之後的所有設定都作用在這個實例上。
你會發現全程沒有呼叫 start(),因為新介面採用了隱式啟動:動畫定義完成後會自動執行。而且這個機制對組合動畫同樣有效——只要還在不斷連綴新方法,動畫就不會立刻開始,等所有方法都設定完畢才一起啟動。當然,你若想顯式呼叫 start() 也完全可以。
此外,ViewPropertyAnimator 的所有介面都用連綴語法設計,每個方法的回傳值都是自己,因此可以一路串下去,一行程式碼完成相當複雜的動畫組合。更多可用的方法,查文件會比死記有用。
寫到這裡,動畫節奏這件事基本就交到你手上了:內建的九種 Interpolator 已經能覆蓋大部分需求,而 getInterpolation() 只有一行,想自創節奏也不難。
Android ViewPager 入門:滑動切換 + 指示標籤
ViewPager 幾乎是所有需要「左右滑動切頁」場景的標配。這篇記錄一下最基礎的用法:把幾個 XML 佈局轉成 View,裝進適配器,再配一條 PagerTabStri
《極簡筆記》原始碼分析(一):從 Manifest 到 MainActivity
《極簡筆記》是一個以 Material Design 與 MVP 架構實作的筆記應用。本文從 Manifest 開始,逐步分析 Application、Activity、
Android 設計理念(下):提升易用性與讓應用更有趣
上一篇介紹了 Android 開發設計理念的一部分,本文繼續說明後續重點,聚焦在易用性、學習成本與使用者情緒。 增加易用性 一致的圖示,一致的功能 使用者應該能透過視覺快
Android 插件化入門:DynamicLoadApk 用法與限制
插件化概念 在大型 Android 專案中,為了縮小 APK 體積,可把不常用功能獨立成插件。當使用者需要時,再從伺服器下載並動態加載。插件本身也是 APK,但通常依賴正