編輯:關於 Android 程式設計
ObjectAnimator 的核心思路很單純:改變物件的屬性,讓系統在改變的過程中幫你補出中間畫面。常用工廠方法包括 ofFloat()、ofInt()、ofObject()、ofArgb() 與 ofPropertyValuesHolder(),下面逐一拆解。
平移、縮放、旋轉、透明度這四種效果,用 ObjectAnimator 都能輕鬆做到,成果與補間動畫相近,但底層機制完全不同。
先準備一個置中的 ImageView:
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ImageView
android:id="@+id/head"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:src="@drawable/head" />
</RelativeLayout>
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_object_animator);
head = (ImageView) findViewById(R.id.head);
}
以下所有動畫都是針對 head 這個 ImageView,本質上就是改它的屬性值。
// 平移
private void translateAnimation() {
ObjectAnimator objectAnimator =
ObjectAnimator.ofFloat(head, "translationX", 0.0f, 350.0f, 0.0f);
objectAnimator.setDuration(2000);
objectAnimator.setRepeatCount(Animation.INFINITE);
objectAnimator.setRepeatMode(Animation.RESTART);
objectAnimator.start();
}
逐行來看。ofFloat 的函式原型是:
public static ObjectAnimator ofFloat(Object target, String propertyName, float... values)
target:動畫作用的物件,這裡是 head。
propertyName:屬性名稱。"translationX" 表示水平位移,"translationY" 則是垂直位移,其他屬性同理。這個字串與 XML 中設定的屬性名一致,例如 android:translationY。
values:動畫的過渡值,可以給 1 到 N 個。只給一個時,該值被視為結束值,起始值由系統從目前狀態取得;給多個時,動畫會依序在這些值之間過渡。本例的三個值 0.0f, 350.0f, 0.0f 意思是由原位右移到 350,再回到 0。
接著是動畫參數設定:
objectAnimator.setDuration(2000); // 時長(毫秒) objectAnimator.setRepeatCount(Animation.INFINITE); // 重複次數 objectAnimator.setRepeatMode(Animation.RESTART); // 重複模式 objectAnimator.start(); // 啟動
// 縮放
private void scaleXAnimation() {
ObjectAnimator objectAnimator =
ObjectAnimator.ofFloat(head, "scaleX", 1.0f, 1.5f);
objectAnimator.setDuration(2000);
objectAnimator.setRepeatCount(Animation.INFINITE);
objectAnimator.setRepeatMode(Animation.RESTART);
objectAnimator.start();
}
// 旋轉
private void rotateAnimation() {
ObjectAnimator objectAnimator =
ObjectAnimator.ofFloat(head, "rotationX", 0.0f, 90.0f, 0.0f);
objectAnimator.setDuration(2000);
objectAnimator.setRepeatCount(Animation.INFINITE);
objectAnimator.setRepeatMode(Animation.RESTART);
objectAnimator.start();
}
// 透明度
private void alphaAnimation() {
ObjectAnimator objectAnimator =
ObjectAnimator.ofFloat(head, "alpha", 1.0f, 0.3f, 1.0f);
objectAnimator.setDuration(2000);
objectAnimator.setRepeatCount(Animation.INFINITE);
objectAnimator.setRepeatMode(Animation.RESTART);
objectAnimator.start();
}
這裡有個容易被忽略的細節:縮放的範例中,圖片放大到 1.5 倍之後就停在該狀態,並沒有回到原樣。原因很直接——過渡值的終值是 1.5f,動畫結束後屬性就是 1.5。這正好說明了屬性動畫與補間動畫最大的差異:屬性動畫是真的改寫了物件屬性,動畫結束後改變會保留;補間動畫則只是「看起來動了」,結束後一律回到初始狀態。其他三個範例之所以會回到原點,是因為我們把終值刻意設成和初始值相同。理解這點,屬性動畫的使用彈性就完全不一樣了。
如果只有上面四種,屬性動畫與補間動畫的差距其實有限。真正的差別在於屬性動畫可以操作任意屬性,例如文字顏色:
<TextView
android:id="@+id/txt"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:text="測試顏色變化"
android:textColor="@android:color/black"
android:textSize="32sp" />
int startColor = 0xffff0000;
int endColor = 0xff00ff00;
ObjectAnimator objectAnimator4 = ObjectAnimator.ofObject(txt, "textColor",
new TypeEvaluator() {
@Override
public Object evaluate(float fraction, Object startValue, Object endValue) {
int startInt = (Integer) startValue;
int startA = (startInt >> 24) & 0xff;
int startR = (startInt >> 16) & 0xff;
int startG = (startInt >> 8) & 0xff;
int startB = startInt & 0xff;
int endInt = (Integer) endValue;
int endA = (endInt >> 24) & 0xff;
int endR = (endInt >> 16) & 0xff;
int endG = (endInt >> 8) & 0xff;
int endB = endInt & 0xff;
return (int) (((startA + (int)(fraction * (endA - startA))) << 24)
| ((startR + (int)(fraction * (endR - startR))) << 16)
| ((startG + (int)(fraction * (endG - startG))) << 8)
| (startB + (int)(fraction * (endB - startB))));
}
}, startColor, endColor);
objectAnimator4.setDuration(3000);
objectAnimator4.start();
ofObject 的原型:
public static ObjectAnimator ofObject(Object target, String propertyName,
TypeEvaluator evaluator, Object... values)
它比 ofFloat 多了一個 TypeEvaluator 參數,用來告訴系統「這個屬性該怎麼過渡」。因為 ofObject 面對的是任意型別,所以必須自己實作評估邏輯;ofFloat 之所以不需要,是因為系統已經內建了 FloatEvaluator。上面這段程式碼做的事就是:把 ARGB 拆成四個通道,按 fraction 逐通道線性插值,再合回一個 int。
除了 textColor,backgroundColor 等屬性也能用同樣手法處理。
顏色動畫其實還有更簡潔的 ofArgb,但這裡要提醒一個實務上的坑:它需要 API 21 以上才支援,而市面上仍有大量低版本機型,專案若要向下相容暫時不宜採用。
ObjectAnimator objectAnimator2 =
ObjectAnimator.ofArgb(txt, "textColor", 0x000, 0x00FF00);
objectAnimator2.start();
setInterpolator():設定插值器,控制變化速率。系統內建的常見選項有 LinearInterpolator(等速)、AccelerateDecelerateInterpolator(先加速後減速)、AccelerateInterpolator(加速)、DecelerateInterpolator(減速)、CycleInterpolator(沿正弦曲線循環指定次數)。
setDuration():動畫時長,單位毫秒。
setRepeatCount():重複次數。大於 0 代表重複幾次,-1 代表無限循環(Animation.INFINITE 就是這個常數,建議直接用常數而非魔術數字),設為 0 則只播放一次。
setRepeatMode():重複模式,可選 RESTART(每次從頭)或 REVERSE(來回播放)。
setStartDelay():延遲啟動,單位毫秒。
setTarget():更換動畫作用物件,效果參數可完全不動:
objectAnimator.setTarget(txt); // 把作用物件由 head 換成 txt
setEvaluator():設定過渡評估器,也就是 TypeEvaluator 物件。
實務上常需要多種效果同時發生,例如水平與垂直同時縮放並繞軸旋轉。這時有三種做法。
AnimatorSet 能讓多個動畫同時或依序執行,靠 play() 串接出時序關係:
after(Animator anim) // 在傳入動畫之後執行 after(long delay) // 延遲指定毫秒後執行 before(Animator anim) // 在傳入動畫之前執行 with(Animator anim) // 與傳入動畫同時執行 playSequentially(Animator... items) // 依序執行
private void multiAnimation() {
ObjectAnimator objectAnimator1 =
ObjectAnimator.ofFloat(head, "scaleX", 1.0f, 2.5f, 1.0f);
ObjectAnimator objectAnimator2 =
ObjectAnimator.ofFloat(head, "scaleY", 1.0f, 2.5f, 1.0f);
ObjectAnimator objectAnimator3 =
ObjectAnimator.ofFloat(head, "rotationX", 0.0f, 90.0f, 0.0f);
AnimatorSet animatorSet = new AnimatorSet();
animatorSet.play(objectAnimator1)
.with(objectAnimator2)
.with(objectAnimator3);
animatorSet.setDuration(2000);
animatorSet.start();
}
只想讓動畫同時播放、不在意串接寫法,也可以用 playTogether:
animatorSet.playTogether(objectAnimator1, objectAnimator2, objectAnimator3);
把多組屬性包成 holder,再交給一個 ObjectAnimator。這種方式只能同時執行,無法排先後順序:
private void multiAnimation2() {
PropertyValuesHolder valuesHolder =
PropertyValuesHolder.ofFloat("scaleX", 1.0f, 2.5f, 1.0f);
PropertyValuesHolder valuesHolder1 =
PropertyValuesHolder.ofFloat("scaleY", 1.0f, 2.5f, 1.0f);
PropertyValuesHolder valuesHolder2 =
PropertyValuesHolder.ofFloat("rotationX", 0.0f, 90.0f, 0.0f);
ObjectAnimator objectAnimator = ObjectAnimator.ofPropertyValuesHolder(
head, valuesHolder, valuesHolder1, valuesHolder2);
objectAnimator.setDuration(2000);
objectAnimator.start();
}
顧名思義,作用對象是 View。當同一個 View 需要同時跑多個屬性動畫時,它是最省字數的選擇,例如右移的同時放大一倍:
private void viewPropertyAnimator() {
ViewPropertyAnimator animator = head.animate();
animator.translationX(200)
.scaleX(2)
.scaleY(2)
.setDuration(2000)
.start();
}
三者如何取捨?AnimatorSet 表達力最強、能排任意時序;PropertyValuesHolder 結構最緊湊,適合單一物件的同時間多屬性;ViewPropertyAnimator 程式碼最短且對 View 有內部優化,適合簡單的複合效果。
實務上除了要動畫,往往還需要在動畫開始、結束、取消、重複時做事,例如結束後再發請求。
private void animationListener() {
ObjectAnimator objectAnimator =
ObjectAnimator.ofFloat(head, "translationX", 0.0f, 350.0f, 0.0f);
objectAnimator.setDuration(2000);
objectAnimator.addListener(new Animator.AnimatorListener() {
@Override public void onAnimationStart(Animator animation) { Log.d("tag", "start"); }
@Override public void onAnimationEnd(Animator animation) { Log.d("tag", "end"); }
@Override public void onAnimationCancel(Animator animation) { Log.d("tag", "cancel"); }
@Override public void onAnimationRepeat(Animator animation) { Log.d("tag", "repeat"); }
});
objectAnimator.start();
}
問題是:大多數時候你只關心其中一個狀態,卻得實作四個方法,程式碼顯得臃腫。Android 提供了更好的解法——AnimatorListenerAdapter:
private void animationListener2() {
ObjectAnimator objectAnimator =
ObjectAnimator.ofFloat(head, "translationX", 0.0f, 350.0f, 0.0f);
objectAnimator.setDuration(2000);
objectAnimator.addListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationEnd(Animator animation) {
super.onAnimationEnd(animation);
Log.d("tag", "end");
}
});
objectAnimator.start();
}
它其實只是一個實作了 AnimatorListener 的抽象類別,需要哪個狀態就覆寫哪個方法,其餘留空即可。
若想取得動畫的每一個中間值,則用 AnimatorUpdateListener:
private void animationListener3() {
ObjectAnimator objectAnimator =
ObjectAnimator.ofFloat(head, "translationX", 0.0f, 350.0f, 0.0f);
objectAnimator.setDuration(2000);
objectAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
@Override
public void onAnimationUpdate(ValueAnimator animation) {
float value = (float) animation.getAnimatedValue();
Log.d("tag", "value=" + value);
}
});
objectAnimator.start();
}
這個介面平常不一定用得上,但做自訂動畫時價值很高——例如讓一個跟隨物件的座標依動畫進度即時計算,就能做出複雜的連動效果。
把動畫寫進 XML 的好處是複用性高、程式碼量小,也讓設計與邏輯分離得更乾淨。
在 res 下建立 animator 資料夾,把 XML 放進去:
android:ordering 控制子動畫的執行順序,sequentially 為順序執行、together 為同時執行:
<set xmlns:android="https://schemas.android.com/apk/res/android"
android:duration="2000"
android:ordering="sequentially">
<!-- 動畫項目 -->
</set>
載入時用 AnimatorInflater,再指定作用物件:
head = (ImageView) findViewById(R.id.head); Animator animator = AnimatorInflater.loadAnimator(this, R.animator.multi); animator.setTarget(head); animator.start();
值得一提的是,XML 中定義的動畫在載入時屬性值可保留彈性——同一個動畫檔套到不同 target 上就能重複使用,這在有多個列表項需要相同進場效果時特別方便。
Android WebView 常見問題與解法整理
混合式 App 常使用 WebView 展示網頁內容。它兼顧動態更新與原生體驗,但也容易遇到相容性與生命週期問題。 錯誤頁與資源清理 可覆寫 onReceivedErr
Android 開發:用 MediaRecorder 錄製影片
MediaRecorder 不只能錄音,也能錄影。整體流程與錄音幾乎一致,差別在於影片必須同時采集聲音與影像兩路資料。 因此除了呼叫 setAudioSource()
三星Root不想失去保固?Towelroot與SuperSU組合教學
三星KNOX會記錄Root與刷機,可能影響保固。若想降低風險,可用Towelroot搭配SuperSU。先執行Towelroot的make it ra1n,重啟後安裝Su
魅族PRO 6與MX6有什麼不同?兩款機型的規格與定位對照
MX6開賣之後,很多人開始在兩者之間猶豫:預算足夠該直接上 PRO 6,還是MX6已經夠用?要回答這個問題,得先看兩台手機各自是怎麼被設計出來的。魅族MX6:把規格做滿的