編輯:關於 Android 程式設計
上一篇談過逐幀動畫(Frame Animation),這次來把補間動畫(Tween Animation)拆解得更細一點。一句話概括:補間動畫是對某個控制項做旋轉、漸變、移動、縮放的轉換過程,可以用 XML 定義,也可以用程式碼實作。
若用 XML,就把動畫定義檔放在 res/anim/ 目錄下,檔名即為資源 ID;若用程式碼,則需要操作 Animation 物件。
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:interpolator="@[package:]anim/interpolator_resource"
android:shareInterpolator=["true" | "false"] >
<alpha
android:fromAlpha="float"
android:toAlpha="float" />
<scale
android:fromXScale="float" android:toXScale="float"
android:fromYScale="float" android:toYScale="float"
android:pivotX="float" android:pivotY="float" />
<translate
android:fromX="float" android:toX="float"
android:fromY="float" android:toY="float" />
<rotate
android:fromDegrees="float" android:toDegrees="float"
android:pivotX="float" android:pivotY="float" />
<set> ... </set>
</set>
根元素可以是 alpha、scale、translate、rotate 中的任何一個,也可以是 set 來管理一個動畫集合(set 本身可以再嵌套 set)。
對應 Java 的 AlphaAnimation,可做出 fadeIn/fadeOut 效果。fromAlpha 為起始透明度、toAlpha 為結束透明度,兩者皆為 0.0(全透明)~1.0(全不透明)的浮點數。
對應 ScaleAnimation。fromXScale/toXScale 是 X 軸方向的相對縮放比例,fromYScale/toYScale 是 Y 軸方向:1.0 代表無變化、0.5 代表縮小一半、2.0 代表放大一倍。pivotX/pivotY 是縮放基準點,若要以圖片中心為基準,兩者都設為 0.5 或 50%。
對應 TranslateAnimation。fromXDelta/toXDelta 為 X 方向起訖位置,fromYDelta/toYDelta 為 Y 方向起訖位置。這四個值支援三種寫法:
對應 RotateAnimation。fromDegrees/toDegrees 為起訖角度(單位:度),pivotX/pivotY 為旋轉中心。pivot 這兩個屬性同樣支援三種寫法:純數字代表相對自身左緣的像素值、num% 代表相對自身左緣/上緣的百分比、num%p 代表相對父容器的百分比。
另外兩個通用屬性:android:fillAfter="true" 表示動畫結束後保持最後狀態;android:duration 設定持續時間(毫秒)。
把 XML 動畫套用到 ImageView 上:
ImageView image = (ImageView) findViewById(R.id.image); Animation testAnim = AnimationUtils.loadAnimation(this, R.anim.test); image.startAnimation(testAnim);
為什麼需要插值器?因為補間動畫通常只定義關鍵幀(首幀或尾幀),中間幀由系統自動補上,這個「補中間值」的過程就叫插值。插值器決定了變化值隨時間的變化規則——是勻速、先加速後減速,還是帶有回彈。
| Interpolator | 資源 ID | 效果 |
|---|---|---|
| AccelerateDecelerateInterpolator | @android:anim/accelerate_decelerate_interpolator | 先加速再減速(預設值) |
| AccelerateInterpolator | @android:anim/accelerate_interpolator | 持續加速 |
| DecelerateInterpolator | @android:anim/decelerate_interpolator | 持續減速 |
| AnticipateInterpolator | @android:anim/anticipate_interpolator | 先往反方向退一小步,再加速前進 |
| AnticipateOvershootInterpolator | @android:anim/anticipate_overshoot_interpolator | 上一個的加強版:超出終點一小步後回到終點 |
| OvershootInterpolator | @android:anim/overshoot_interpolator | 快速衝過終點,再彈回 |
| BounceInterpolator | @android:anim/bounce_interpolator | 最後階段加入彈跳效果 |
| CycleInterpolator | @android:anim/cycle_interpolator | 週期性往返運動 |
| LinearInterpolator | @android:anim/linear_interpolator | 勻速 |
使用方式有兩種層級。直接在動畫元素上引用:
<set android:interpolator="@android:anim/accelerate_interpolator"> ... </set>
<alpha android:interpolator="@android:anim/accelerate_interpolator" ... />
若要調整參數(例如加速倍率、回彈張力),就得自訂一個插值器資源。常見的可調屬性:
| 標籤 | 可調屬性 |
|---|---|
| <accelerateDecelerateInterpolator> | 無 |
| <accelerateInterpolator> | android:factor(浮點,加速倍率,預設 1) |
| <decelerateInterpolator> | android:factor(浮點,減速率,預設 1) |
| <anticipateInterpolator> | android:tension(浮點,後退張力,預設 2) |
| <anticipateOvershootInterpolator> | android:tension(預設 2)、android:extraTension(倍數,預設 1.5,實際為 2 × 1.5) |
| <overshootInterpolator> | android:tension(浮點,超出終點的張力,預設 2) |
| <cycleInterpolator> | android:cycles(整數,循環次數,預設 1) |
| <bounceInterpolator> / <linearInterpolator> | 無 |
例如自訂一個張力更誇張的 overshoot:
<?xml version="1.0" encoding="utf-8"?>
<overshootInterpolator xmlns:android="https://schemas.android.com/apk/res/android"
android:tension="7.0"/>
存為 res/anim/my_overshoot_interpolator.xml 後即可引用:
<scale xmlns:android="https://schemas.android.com/apk/res/android"
android:interpolator="@anim/my_overshoot_interpolator" ... />
若內建的九種都不夠用,可以直接實作 Interpolator 介面。所有插值器都實作了它,而介面裡只有一個方法:
float getInterpolation(float input);
參數 input 代表動畫進度,範圍 0~1(起始到結束)。實作範例:
/** 勻速 */
public float getInterpolation(float input) {
return input;
}
/** 先加速後減速(餘弦曲線) */
public float getInterpolation(float input) {
return (float) (Math.cos((input + 1) * Math.PI) / 2.0f) + 0.5f;
}
版面 res/layout/rotate.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<ImageView
android:id="@+id/piechart"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:src="@drawable/piechart"/>
<Button
android:id="@+id/positive"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="順時針"
android:onClick="positive"/>
<Button
android:id="@+id/negative"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="逆時針"
android:onClick="negative"/>
</LinearLayout>
動畫定義 res/anim/rotate.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/accelerate_decelerate_interpolator">
<rotate
android:fromDegrees="0"
android:toDegrees="+360"
android:pivotX="50%"
android:pivotY="50%"
android:duration="5000"/>
</set>
RotateActivity.java(程式碼版,可連續累加角度):
public class RotateActivity extends Activity {
private int currAngle;
private View piechart;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.rotate);
piechart = findViewById(R.id.piechart);
Animation animation = AnimationUtils.loadAnimation(this, R.anim.rotate);
piechart.startAnimation(animation);
}
/** 順時針轉 180 度 */
public void positive(View v) {
Animation anim = new RotateAnimation(currAngle, currAngle + 180,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
anim.setInterpolator(new LinearInterpolator());
anim.setDuration(1000);
anim.setFillAfter(true); // 動畫結束後保持最終狀態
currAngle = (currAngle + 180) % 360;
piechart.startAnimation(anim);
}
/** 逆時針轉 180 度 */
public void negative(View v) {
Animation anim = new RotateAnimation(currAngle, currAngle - 180,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
anim.setInterpolator(new LinearInterpolator());
anim.setDuration(1000);
anim.setFillAfter(true);
currAngle = (currAngle - 180) % 360;
piechart.startAnimation(anim);
}
}
版面 res/layout/alpha.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="#FFFFFF">
<ImageView
android:id="@+id/splash"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_gravity="center"
android:src="@drawable/splash"/>
<Button
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="alpha"
android:onClick="alpha"/>
</FrameLayout>
動畫定義 res/anim/alpha.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android">
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="3000"/>
</set>
AlphaActivity.java(示範 AnimationListener 的三個回呼):
public class AlphaActivity extends Activity implements Animation.AnimationListener {
private ImageView splash;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.alpha);
splash = (ImageView) findViewById(R.id.splash);
Animation anim = AnimationUtils.loadAnimation(this, R.anim.alpha);
anim.setAnimationListener(this);
splash.startAnimation(anim);
}
/** 點擊後反向淡出 */
public void alpha(View view) {
Animation anim = new AlphaAnimation(1.0f, 0.0f);
anim.setDuration(3000);
anim.setFillAfter(true);
splash.startAnimation(anim);
}
@Override public void onAnimationStart(Animation animation) {
Log.i("alpha", "onAnimationStart called.");
}
@Override public void onAnimationEnd(Animation animation) {
Log.i("alpha", "onAnimationEnd called");
}
@Override public void onAnimationRepeat(Animation animation) {
Log.i("alpha", "onAnimationRepeat called");
}
}
版面 res/layout/translate.xml:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/trans_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/person"/>
<Button
android:id="@+id/trans_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="translate"
android:onClick="translate"/>
</FrameLayout>
動畫定義 res/anim/translate.xml:
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/bounce_interpolator">
<translate
android:fromXDelta="0" android:fromYDelta="0"
android:toXDelta="200" android:toYDelta="300"
android:duration="2000"/>
</set>
TranslateActivity.java:
public class TranslateActivity extends Activity {
private ImageView trans_image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.translate);
trans_image = (ImageView) findViewById(R.id.trans_image);
Animation anim = AnimationUtils.loadAnimation(this, R.anim.translate);
anim.setFillAfter(true);
trans_image.startAnimation(anim);
}
/** 用 OvershootInterpolator 彈回原點 */
public void translate(View view) {
Animation anim = new TranslateAnimation(200, 0, 300, 0);
anim.setDuration(2000);
anim.setFillAfter(true);
anim.setInterpolator(new OvershootInterpolator());
trans_image.startAnimation(anim);
}
}
版面 res/layout/scale.xml:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="@+id/scale_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:src="@drawable/person"/>
<Button
android:id="@+id/scale_button"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_gravity="bottom"
android:text="scale"
android:onClick="sclae"/>
</LinearLayout>
動畫定義 res/anim/scale.xml(縮放與漸變同時進行):
<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:interpolator="@android:anim/bounce_interpolator">
<scale
android:fromXScale="1.0" android:toXScale="2.0"
android:fromYScale="1.0" android:toYScale="2.0"
android:pivotX="0.5" android:pivotY="50%"
android:duration="2000"/>
<alpha android:fromAlpha="0.0" android:toAlpha="1.0" android:duration="3000"/>
</set>
ScaleActivity.java:
public class ScaleActivity extends Activity {
private ImageView scale_image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.scale);
scale_image = (ImageView) findViewById(R.id.scale_image);
Animation anim = AnimationUtils.loadAnimation(this, R.anim.scale);
anim.setFillAfter(true);
scale_image.startAnimation(anim);
}
/** 從 2 倍縮回 1 倍,帶回彈效果 */
public void sclae(View view) {
Animation anim = new ScaleAnimation(2.0f, 1.0f, 2.0f, 1.0f,
Animation.RELATIVE_TO_SELF, 0.5f,
Animation.RELATIVE_TO_SELF, 0.5f);
anim.setDuration(2000);
anim.setFillAfter(true);
anim.setInterpolator(new BounceInterpolator());
scale_image.startAnimation(anim);
}
}
四種動畫的執行效果:




這是新手最容易誤解的一點。補間動畫走的是「繪製時套用矩陣變換」的路子,View 的 getLeft()、getTop() 從頭到尾都沒變。因此你會看到:圖片明明已經移動到別的位置,但點擊事件仍然觸發在原來的地方。
若需要「動畫結束後位置真的改變、事件區域也跟著移動」,請改用屬性動畫(ObjectAnimator/ValueAnimator)。它直接修改 View 的屬性值,能與版面配置、事件分發正確協同,也是 Android 3.0 以後官方主推的方案。補間動畫則適合用在「純視覺、不需要互動」的場合,例如開屏淡入、Loading 旋轉等。
Android ViewPager 使用方法詳解
ViewPager 是實作左右滑動切頁最常見的元件,核心在於三件事:準備好要切換的 View 清單、寫一個 PagerAdapter、然後掛到 ViewPager 上。
Android 自訂 View 實作四碼驗證碼
登入、註冊頁面幾乎都會放一個驗證碼。自己動手做一個其實不難,拆成「產生隨機字元」與「自繪 Drawable」兩塊即可。 效果如下: 一、隨機產生四個字母 把 2
RecyclerView 實作複雜首頁布局的三種方式
電商、影音與內容平台的首頁,經常需要同時呈現橫幅、列表、網格與瀑布流。本文以 RecyclerView 為核心,整理三種常見實作方式,並比較其適用性。 方案一:Rec
Android 螢幕亮度自動調節流程解析
Android 的螢幕亮度自動調節,核心在於光線感測器與系統設定檔的配合。當使用者開啟自動亮度後,系統會依環境光線动态调整背光。 在設定層面,BrightnessPref