編輯:關於 Android 程式設計
在 Android 3.0 之前,系統只提供兩套動畫方案:補間動畫(Tween Animation)與幀動畫(Frame Animation)。到了 3.0,Google 引入了全新的屬性動畫(Property Animation)系統。對應到 SDK 的命名體系,這三者分別被稱為 View Animation、Drawable Animation 與 Property Animation。
理解它們的差異,是掌握 Android 動畫的第一步:
補間動畫可以再細分為四類:透明度動畫(Alpha)、尺寸伸縮動畫(Scale)、位置移動動畫(Translate)與旋轉動畫(Rotate)。
補間動畫的本質,是對一個 View 的外觀做一連串變換:放大縮小、改變透明度、平移位置、旋轉角度。定義方式有 Java 程式碼與 XML 兩種,官方建議優先使用 XML,因為它把動畫參數與業務邏輯分離,可讀性與維護性都更好。
XML 檔案放置於 /res/anim/ 目錄,根元素為 <set>,允許的子節點包括 <alpha>、<scale>、<translate>、<rotate>。
duration(long):動畫持續時間,單位為毫秒。fillAfter(boolean):設為 true 時,動畫結束後仍套用轉換結果。fillBefore(boolean):設為 true 時,動畫開始前先套用轉換結果。interpolator:指定插值器,控制速度曲線,常見的有 accelerate_decelerate_interpolator(先加速再減速)、accelerate_interpolator(加速)、decelerate_interpolator(減速)。repeatCount(int):動畫重複次數。repeatMode(String):重複行為,可選 restart 或 reverse,例如 android:repeatMode="reverse"。fromAlpha:起始透明度,0.0 代表全透明,1.0 代表完全不透明,取值範圍 0.0~1.0。toAlpha:結束時的透明度。fromXScale、fromYScale:起始的 X、Y 軸伸縮比例。0.0 表示收縮到看不見,1.0 表示原始尺寸,小於 1.0 為縮小,大於 1.0 為放大。toXScale、toYScale:結束時的伸縮比例。pivotX、pivotY:伸縮的基準點,取值 0%~100%,50% 即為 View 寬或高的中點。<scale
android:duration="700"
android:fillAfter="false"
android:fromXScale="0.0"
android:fromYScale="0.0"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:repeatCount="10"
android:startOffset="700"
android:toXScale="1.4"
android:toYScale="1.4" />
fromXDelta、toXDelta:動畫起訖時在 X 軸上的位置。fromYDelta、toYDelta:動畫起訖時在 Y 軸上的位置。fromDegrees:起始角度。負值代表逆時針,正值代表順時針。toDegrees:結束角度,數值可以超過 360 度。pivotX、pivotY:旋轉中心,取值 0%~100%,50% 為中點。角度方向的組合關係可以這樣記:起訖同為正值或同為負值時依號碼方向旋轉,而「負值到正值」為順時針、「正值到負值」為逆時針。
<rotate
android:duration="2000"
android:fromDegrees="0"
android:interpolator="@android:anim/accelerate_decelerate_interpolator"
android:pivotX="50%"
android:pivotY="50%"
android:toDegrees="+250" />
除了 XML,也可以直接建立對應的 Animation 物件。以下是常見寫法:
public class MainActivity extends AppCompatActivity {
private ImageView iv;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv = findViewById(R.id.iv);
}
// 位移:依序為 X 起點、X 終點、Y 起點、Y 終點
public void translateClick1(View view) {
TranslateAnimation ta = new TranslateAnimation(0, 200, 0, 200);
ta.setDuration(5000);
ta.setFillAfter(true); // 結束後保持最後狀態
iv.startAnimation(ta);
}
// 透明度:1 為不透明,0 為全透明
public void alphaClick1(View view) {
AlphaAnimation aa = new AlphaAnimation(1, 0);
aa.setDuration(3000);
iv.startAnimation(aa);
}
// 縮放:後四個參數為縮放中心
public void scaleClick1(View view) {
ScaleAnimation sa = new ScaleAnimation(0, 1, 0, 1,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
sa.setDuration(3000);
iv.startAnimation(sa);
}
// 旋轉:可設定重複次數與重複模式
public void rotateClick1(View view) {
RotateAnimation ra = new RotateAnimation(0, 359,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
ra.setRepeatCount(RotateAnimation.INFINITE);
ra.setRepeatMode(RotateAnimation.REVERSE);
ra.setDuration(3000);
iv.startAnimation(ra);
}
// 組合動畫
public void setClick1(View view) {
AnimationSet set = new AnimationSet(true); // true 表示共用同一個插值器
TranslateAnimation ta = new TranslateAnimation(0, iv.getWidth(), 0, iv.getHeight());
ta.setDuration(3000);
set.addAnimation(ta);
AlphaAnimation aa = new AlphaAnimation(0.2f, 0.8f);
aa.setDuration(3000);
set.addAnimation(aa);
ScaleAnimation sa = new ScaleAnimation(1, 2, 1, 2,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f,
ScaleAnimation.RELATIVE_TO_SELF, 0.5f);
sa.setDuration(3000);
set.addAnimation(sa);
RotateAnimation ra = new RotateAnimation(0, -359,
RotateAnimation.RELATIVE_TO_SELF, 0.5f,
RotateAnimation.RELATIVE_TO_SELF, 0.5f);
ra.setDuration(3000);
set.addAnimation(ra);
iv.startAnimation(set);
}
// 載入 XML 動畫資源
public void translateClick2(View view) {
Animation animation = AnimationUtils.loadAnimation(this, R.anim.translate_anim);
animation.setFillAfter(true);
iv.startAnimation(animation);
}
}
AccelerateDecelerateInterpolator:頭尾較慢,中段加速。AccelerateInterpolator:起步慢,之後持續加速。DecelerateInterpolator:起步快,之後逐漸減速。BounceInterpolator:結束時有彈跳效果。CycleInterpolator:沿正弦曲線循環播放指定次數。LinearInterpolator:等速變化。幀動畫對應 AnimationDrawable 物件,原理和 GIF 幾乎一致:把一系列 Drawable 依序顯示,靠快速切換製造動態錯覺。XML 需以 <animation-list> 為根元素,每個 <item> 描述一幀,透過 duration 指定該幀停留時間,檔案放在 /res/anim/ 或 /res/animator/ 目錄。
<animation-list xmlns:android="https://schemas.android.com/apk/res/android"
android:oneshot="true">
<item android:drawable="@drawable/p0" android:duration="200" />
<item android:drawable="@drawable/p1" android:duration="200" />
<item android:drawable="@drawable/p2" android:duration="200" />
<item android:drawable="@drawable/p3" android:duration="200" />
<item android:drawable="@drawable/p4" android:duration="200" />
</animation-list>
三個關鍵屬性:drawable 指定該幀使用的圖片資源;duration 指定顯示時間(毫秒);oneshot 為 true 時只播放一次並停在最後一幀,為 false 則無限循環。
ad = (AnimationDrawable) iv1.getDrawable();
iv1.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
if (ad.isRunning()) {
ad.stop(); // 播放中再次點擊則先停止
}
ad.start();
}
});
官方文件特別提醒:不要在 onCreate() 中呼叫 start(),因為此時 AnimationDrawable 尚未與 Window 完成關聯。若希望畫面一出現就開始播放,應改在 onWindowFocusChanged() 中啟動。
屬性動畫在 Android 3.0 才登場,顧名思義,它是透過動畫去改變「物件的實際屬性」。補間動畫只改變 View 的繪製結果,View 本身的屬性並未變動,因此會出現一個經典陷阱:無論你把 Button 縮放得多大,真正可點擊的範圍仍然是動畫之前的區域。
屬性動畫不同,它改的是真實數值。Button 縮放後,其位置與大小的屬性值確實改變了,點擊熱區也跟著變。更強的是,屬性動畫的對象不限於 View,任何 Java 物件都能使用——它只負責讓某個值在一段時間內平滑變化,至於值變了要做什麼,完全由你決定。
Duration:持續時間,預設 300ms,對應 android:duration。Time interpolation:時間插值器,定義變化率,對應 android:interpolator。Repeat count and behavior:重複次數與模式,可選擇重頭開始或反向播放,對應 android:repeatCount。Animator sets:動畫集合,透過 android:ordering 決定同group動畫是同時執行還是依序執行。Frame refresh delay:幀刷新延遲,預設 10ms,實際仍取決於系統當前負載。ObjectAnimator:ValueAnimator 的子類,指定目標物件與屬性名稱即可,最常用。ValueAnimator:更底層的執行類,需自行在更新回呼中處理數值,適合 ObjectAnimator 無法覆蓋的少數場景。AnimatorSet:控制一組動畫的執行方式,可同時、可順序。整體流程是:由動畫執行類指定操作對象、屬性名稱、起訖值與持續時間,系統便會依參數動態驅動該屬性變化。
public class MainActivity extends AppCompatActivity {
private ImageView iv1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
iv1 = findViewById(R.id.iv1);
// 版面元素的入場動畫
LinearLayout linearLayout = findViewById(R.id.ll);
ScaleAnimation sa = new ScaleAnimation(0, 1, 0, 1);
sa.setDuration(500);
// delay 為 0 表示同時播放,0.5f 表示每個子項延遲 0.5 秒
LayoutAnimationController lac = new LayoutAnimationController(sa, 0.5f);
lac.setOrder(LayoutAnimationController.ORDER_RANDOM);
linearLayout.setLayoutAnimation(lac);
}
// 位移
public void translateClick(View view) {
ObjectAnimator oa = ObjectAnimator.ofFloat(iv1, "translationX", 0, 200, 0);
oa.setDuration(5000);
oa.start();
}
// 透明度
public void alphaClick(View view) {
ObjectAnimator oa = ObjectAnimator.ofFloat(iv1, "alpha", 0f, 0.5f, 0f, 1f);
oa.setDuration(5000);
oa.start();
}
// 縮放
public void scaleClick(View view) {
ObjectAnimator oa = ObjectAnimator.ofFloat(iv1, "scaleX", 0, 1, 0.5f, 1);
oa.setDuration(5000);
oa.start();
}
// 旋轉:rotation 繞中心點,rotateX 繞 X 軸,rotateY 繞 Y 軸
public void rotateClick(View view) {
ObjectAnimator oa = ObjectAnimator.ofFloat(iv1, "rotation", 0, 359);
oa.setRepeatCount(ObjectAnimator.INFINITE);
oa.setRepeatMode(ObjectAnimator.RESTART);
oa.setInterpolator(new LinearInterpolator());
oa.setDuration(5000);
oa.start();
}
// 組合動畫
public void animClick1(View view) {
PropertyValuesHolder pv1 = PropertyValuesHolder.ofFloat("rotation", 0, 359);
PropertyValuesHolder pv2 = PropertyValuesHolder.ofFloat("scaleX", 1, 2);
PropertyValuesHolder pv3 = PropertyValuesHolder.ofFloat("translationX", 0, 200);
PropertyValuesHolder pv4 = PropertyValuesHolder.ofFloat("alpha", 0.5f, 1f);
ObjectAnimator oa = ObjectAnimator.ofPropertyValuesHolder(iv1, pv1, pv2, pv3, pv4);
oa.setDuration(5000);
oa.start();
}
// 針對自訂物件做動畫
public void animClick2(View view) {
MyImageView miv = new MyImageView(iv1);
ObjectAnimator oa = ObjectAnimator.ofInt(miv, "height", 0, 200);
oa.setDuration(5000);
oa.start();
}
}
需要特別注意的是,若自訂物件要支援屬性動畫,必須提供對應的 setter 方法(如 setHeight()),否則動畫無法生效。
Android 5.0 共享元素轉場動畫實戰:從 RecyclerView 到詳情頁的平滑過渡
Android 5.0 共享元素轉場動畫實戰 Android 5.0 以後,Activity 轉場動畫變得相當容易。只要使用 ActivityOptionsCompat
重寫 MPAndroidChart:解決 MarkView 在圖表邊緣被裁切的問題
MPAndroidChart 是繪製圖表相當趁手的開源庫,多數常見需求都能覆蓋。但當你準備改造第三方元件時,比較好的做法始終是「繼承擴展」,而不是把原始碼整包複製到自己的
Android 自訂 ListView 實作下拉刷新與上拉載入更多
下拉刷新、上拉載入更多,幾乎是每個資訊類 App 的標配。與其每次重造輪子,不如把這個行為封裝成一個可直接替換 ListView 的 DynamicListView。
Android 自定義 View 之酷炫數字圓環動畫
先看最終效果: 一、開始實現 新建一個 DoughnutView 繼承自 View: public class DoughnutView extends View {