編輯:關於 Android 程式設計
最近對 Android 的動畫特別感興趣,大概是因為自己偏愛跟 UI 打交道的緣故。這篇文章想聊一個常被忽略、卻極其實用的類:ViewPropertyAnimator。
這個類的存在,是 Google 為了簡化 View 屬性動畫而做的一層封裝。它把冗長的 ObjectAnimator 組合濃縮成一行流式調用,讓屬性動畫的門檻大幅降低。
閱讀本文前,建議先對屬性動畫有基本認知,否則不容易理解這層封裝究竟省掉了哪些麻煩。
順帶一提,Android 的動畫大致分為補間動畫、幀動畫、屬性動畫三類,後來又多了一種 SVG 矢量動畫。本文只聚焦屬性動畫的這一分支。
先說構造方法。這個類專門處理 View 的屬性動畫,所以對象的創建必須依附於 View。
/**
* 返回與當前 View 關聯的 ViewPropertyAnimator 對象
*/
public ViewPropertyAnimator animate() {
if (mAnimator == null) {
mAnimator = new ViewPropertyAnimator(this);
}
return mAnimator;
}
我們通過 view.animate() 拿到實例,之後調用的每個方法返回值都是 ViewPropertyAnimator 本身,因此可以連綴式寫法一路點下去。
// 關聯的 View 對象
private final View mView;
// 動畫時長,以及是否已顯式設置過
private long mDuration;
private boolean mDurationSet = false;
// 開始延遲,以及是否已顯式設置過
private long mStartDelay = 0;
private boolean mStartDelaySet = false;
// 差值器,以及是否已顯式設置過
private TimeInterpolator mInterpolator;
private boolean mInterpolatorSet = false;
// 動畫監聽器
private Animator.AnimatorListener mListener = null;
private AnimatorEventListener mAnimatorEventListener = new AnimatorEventListener();
// 待執行動畫的屬性/數值對集合
ArrayList<NameValuesHolder> mPendingAnimations = new ArrayList<>();
// 各階段的待執行任務
private Runnable mPendingSetupAction;
private Runnable mPendingCleanupAction;
private Runnable mPendingOnStartAction;
private Runnable mPendingOnEndAction;
// View 常見屬性用位掩碼表示
private static final int NONE = 0x0000;
private static final int TRANSLATION_X = 0x0001;
private static final int TRANSLATION_Y = 0x0002;
private static final int SCALE_X = 0x0004;
private static final int SCALE_Y = 0x0008;
private static final int ROTATION = 0x0010;
private static final int ROTATION_X = 0x0020;
private static final int ROTATION_Y = 0x0040;
private static final int X = 0x0080;
private static final int Y = 0x0100;
private static final int ALPHA = 0x0200;
// 真正啟動動畫的任務
private Runnable mAnimationStarter = new Runnable() {
@Override
public void run() {
startAnimation();
}
};
這裡有兩個關鍵的內部類。第一個是 PropertyBundle,用位掩碼描述「這一批動畫涉及哪些屬性」,並持有對應的屬性/數值列表,同時提供 cancel(int) 方法用于把某個屬性從批次裡摘出去。
private static class PropertyBundle {
int mPropertyMask;
ArrayList<NameValuesHolder> mNameValuesHolder;
boolean cancel(int propertyConstant) {
if ((mPropertyMask & propertyConstant) != 0 && mNameValuesHolder != null) {
int count = mNameValuesHolder.size();
for (int i = 0; i < count; ++i) {
NameValuesHolder nv = mNameValuesHolder.get(i);
if (nv.mNameConstant == propertyConstant) {
mNameValuesHolder.remove(i);
mPropertyMask &= ~propertyConstant;
return true;
}
}
}
return false;
}
}
第二個是 NameValuesHolder,它持有「要改哪個屬性、從多少改到多少」這組信息。
private static class NameValuesHolder {
int mNameConstant;
float mFromValue;
float mDeltaValue;
NameValuesHolder(int nameConstant, float fromValue, float deltaValue) {
mNameConstant = nameConstant;
mFromValue = fromValue;
mDeltaValue = deltaValue;
}
}
此外還有五個 Map,分別把 Animator 與 PropertyBundle、以及 setup / cleanup / onStart / onEnd 四類任務關聯起來,便於統一管理:
private HashMap<Animator, PropertyBundle> mAnimatorMap;
private HashMap<Animator, Runnable> mAnimatorSetupMap;
private HashMap<Animator, Runnable> mAnimatorCleanupMap;
private HashMap<Animator, Runnable> mAnimatorOnStartMap;
private HashMap<Animator, Runnable> mAnimatorOnEndMap;
構造方法被設計成包可見(而非 public),強制使用者只能通過 View.animate() 取得實例:
ViewPropertyAnimator(View view) {
mView = view;
view.ensureTransformationInfo();
}

類中提供了一整套針對 View 屬性的設置方法,返回值都是 ViewPropertyAnimator,所以能連綴。挑 alpha 看看:
public ViewPropertyAnimator alpha(float value) {
animateProperty(ALPHA, value);
return this;
}
跟進 animatePropertyBy:
private void animatePropertyBy(int constantName, float startValue, float byValue) {
// 先取消該屬性上正在執行的動畫
if (mAnimatorMap.size() > 0) {
Animator animatorToCancel = null;
Set<Animator> animatorSet = mAnimatorMap.keySet();
for (Animator runningAnim : animatorSet) {
PropertyBundle bundle = mAnimatorMap.get(runningAnim);
if (bundle.cancel(constantName)) {
// 該屬性已被移除,若這批動畫已無任何屬性可改,則整個取消
if (bundle.mPropertyMask == NONE) {
animatorToCancel = runningAnim;
break;
}
}
}
if (animatorToCancel != null) {
animatorToCancel.cancel();
}
}
// 封裝待處理的屬性/數值對,並提交到主線程隊列
NameValuesHolder nameValuePair = new NameValuesHolder(constantName, startValue, byValue);
mPendingAnimations.add(nameValuePair);
mView.removeCallbacks(mAnimationStarter);
mView.post(mAnimationStarter);
}
這段邏輯做了三件事:取消同屬性上的舊動畫、把新的屬性與數值封裝進 mPendingAnimations、最後通過 View.post 把啟動任務拋回主線程。這樣做的意義是保證所有屬性設置都在主線程串行執行,避免手忙腳亂地創建多個動畫器。
/**
* 啟動底層 Animator。這裡只用了「一個」從 0 到 1 的
* ValueAnimator,再用這個分數值去驅動各個屬性
*/
private void startAnimation() {
mView.setHasTransientState(true);
ValueAnimator animator = ValueAnimator.ofFloat(1.0f);
ArrayList<NameValuesHolder> nameValueList =
(ArrayList<NameValuesHolder>) mPendingAnimations.clone();
mPendingAnimations.clear();
int propertyMask = 0;
int propertyCount = nameValueList.size();
for (int i = 0; i < propertyCount; ++i) {
propertyMask |= nameValueList.get(i).mNameConstant;
}
mAnimatorMap.put(animator, new PropertyBundle(propertyMask, nameValueList));
if (mPendingSetupAction != null) {
mAnimatorSetupMap.put(animator, mPendingSetupAction);
mPendingSetupAction = null;
}
if (mPendingCleanupAction != null) {
mAnimatorCleanupMap.put(animator, mPendingCleanupAction);
mPendingCleanupAction = null;
}
if (mPendingOnStartAction != null) {
mAnimatorOnStartMap.put(animator, mPendingOnStartAction);
mPendingOnStartAction = null;
}
if (mPendingOnEndAction != null) {
mAnimatorOnEndMap.put(animator, mPendingOnEndAction);
mPendingOnEndAction = null;
}
animator.addUpdateListener(mAnimatorEventListener);
animator.addListener(mAnimatorEventListener);
if (mStartDelaySet) animator.setStartDelay(mStartDelay);
if (mDurationSet) animator.setDuration(mDuration);
if (mInterpolatorSet) animator.setInterpolator(mInterpolator);
animator.start();
}
值得注意的是那三個 *Set 布爾標志。因為屬性方法可以連綴調用,如果每次都無條件 setDuration,後面沒設置的屬性就會把前面的設置覆蓋成默認值。用標志位記錄「用戶到底有沒有設過」,是這套封裝能正確工作的關鍵細節。
除了常用的屬性方法,ViewPropertyAnimator 還提供了 withLayer、withStartAction、withEndAction 等豐富動畫效果的接口。而且動畫會自動啟動,不需要手動調 start()(當然也可以顯式調用),同時支持取消與實時監聽。
textview.animate()
.x(500)
.y(500)
.setDuration(5000)
.setInterpolator(new BounceInterpolator());
ViewPropertyAnimator 對日常寫屬性動畫的幫助很大:更簡短、更易讀,代碼也更乾淨。但它的作用範圍僅限於 View,不像 ValueAnimator 那樣能針對任意對象。所以實踐中的判斷很簡單——改 View 的屬性就用它,改其他對象則回到 ValueAnimator。
Android 系統應用開發(五):Android 輸入法類別與元件說明
前言Android 原始碼中的 packages/inputmethods 收錄了多套輸入法實作,包含 OpenWNN、LatinIME 與 Google PinyinI
Socket 實作手機與電腦檔案互傳(一):讀取本機各類檔案資源
好久沒寫文章了,這陣子都在做一個比賽專案:手機端與 PC 端互傳檔案。剛看到題目時完全沒頭緒,查了資料和書籍後才確認可以用 Socket 建立連線、再透過 IO 串流搬運
天翼4G+是什麼?載波聚合技術與使用條件解析
天翼4G+是中國電信的4G升級方案,核心為載波聚合技術,理論峰值可達300Mbps。 要使用4G+,手機需支援CA,當地也必須有4G+訊號。部分新機已推出,但實際速度仍受
Android Studio 性能監控(三):CPU Monitor 快速上手
Android Monitor 面板中集成了一個 CPU Monitor,可以讓開發者在真機或模擬器上實時觀察應用的 CPU 佔用情況,對於排查卡頓、定位異常耗電都有幫助