編輯:關於 Android 程式設計
Scroller 是 Android 中用來輔助 View 平滑移動的類別。對剛接觸它的人來說,往往有兩個疑問纏身:
要回答這兩題,得從 View 的繪製流程切進去。網路上關於繪製流程的文章很多,內容大同小異,這裡只摘出理解 Scroller 必要的幾個環節:
scrollTo()/scrollBy() → invalidate()/postInvalidate() → computeScroll()
scrollTo 與 scrollBy 是 View 移動的兩個方法,它們更新 View 的新座標,接著呼叫 invalidate 或 postInvalidate 刷新畫面;滑動結束後再呼叫 computeScroll()。而 computeScroll() 在 View.java 裡只是一個空方法,內容要由我們自己填。
問:如果在 computeScroll() 裡呼叫 scrollTo/scrollBy,會怎樣?
答:形成一個死循環,在同一個位置不斷刷新 View。只是因為系統的緩存與優化機制,肉眼看不出它在刷而已。
問:如果在 computeScroll() 裡呼叫 scrollTo/scrollBy,同時持續改變 Y 座標呢?
答:一樣是死循環刷新,但因為 Y 座標一直在變,View 就會依座標規律上下移動。只要這個變化是有節奏的、慢慢遞進的,就達成了我們要的效果——平滑移動。
有種撥雲見日的感覺。與其說 Scroller 是「View 平滑移動的輔助類」,不如說它是一個「按時間產生座標的計算器」。Scroller 跟 View 的滑動本身其實沒有直接關係,它只負責算出動畫在某個時間點該落在哪個位置,形成一條座標路線;View 沿著這條路線反覆 invalidate,畫面上看起來就是平滑移動了。
public void startScroll(int startX, int startY, int dx, int dy, int duration) {
mMode = SCROLL_MODE;
mFinished = false;
mDuration = duration;
mStartTime = AnimationUtils.currentAnimationTimeMillis();
mStartX = startX;
mStartY = startY;
mFinalX = startX + dx;
mFinalY = startY + dy;
mDeltaX = dx;
mDeltaY = dy;
mDurationReciprocal = 1.0f / (float) mDuration;
}
簡單到令人難以置信:只是設定了動畫起始時間、起點座標、終點座標和時長倒數(純粹為了後續計算方便)。但動畫其實已經「開始」了,只是還沒畫到螢幕上。因為記住了起始時間,Scroender 就能依時間差算出目前應有的座標,View 拿這個座標去 invalidate 就動起來了。
影響座標計算的另一個關鍵是插值器。在 public Scroller(Context context, Interpolator interpolator) 這個建構子裡有相關說明,也可以自帶自訂的 Interpolator,這裡不展開。
public boolean computeScrollOffset() {
if (mFinished) {
return false;
}
int timePassed = (int)(AnimationUtils.currentAnimationTimeMillis() - mStartTime);
if (timePassed < mDuration) {
switch (mMode) {
case SCROLL_MODE:
float x = timePassed * mDurationReciprocal;
if (mInterpolator == null)
x = viscousFluid(x);
else
x = mInterpolator.getInterpolation(x);
mCurrX = mStartX + Math.round(x * mDeltaX);
mCurrY = mStartY + Math.round(x * mDeltaY);
break;
case FLING_MODE:
final float t = (float) timePassed / mDuration;
final int index = (int) (NB_SAMPLES * t);
final float t_inf = (float) index / NB_SAMPLES;
final float t_sup = (float) (index + 1) / NB_SAMPLES;
final float d_inf = SPLINE[index];
final float d_sup = SPLINE[index + 1];
final float distanceCoef = d_inf + (t - t_inf) / (t_sup - t_inf) * (d_sup - d_inf);
mCurrX = mStartX + Math.round(distanceCoef * (mFinalX - mStartX));
mCurrX = Math.min(mCurrX, mMaxX);
mCurrX = Math.max(mCurrX, mMinX);
mCurrY = mStartY + Math.round(distanceCoef * (mFinalY - mStartY));
mCurrY = Math.min(mCurrY, mMaxY);
mCurrY = Math.max(mCurrY, mMinY);
if (mCurrX == mFinalX && mCurrY == mFinalY) {
mFinished = true;
}
break;
}
} else {
mCurrX = mFinalX;
mCurrY = mFinalY;
mFinished = true;
}
return true;
}
重點在於:動畫還沒結束就算出目前座標,結束了就直接把座標拉到終點並標記完成。這裡有 SCROLL_MODE(手動拖曳的平滑模式)與 FLING_MODE(依手指滑動速率判斷的慣性模式)兩種分支。這個方法跑完後,通常根據回傳值決定要不要 invalidate,再由 View 把 scrollTo/scrollBy 移動到 Scroller 算好的新座標。
public void fling(int startX, int startY, int velocityX, int velocityY,
int minX, int maxX, int minY, int maxY) {
// Continue a scroll or fling in progress
if (mFlywheel && !mFinished) {
float oldVel = getCurrVelocity();
float dx = (float) (mFinalX - mStartX);
float dy = (float) (mFinalY - mStartY);
float hyp = FloatMath.sqrt(dx * dx + dy * dy);
float ndx = dx / hyp;
float ndy = dy / hyp;
float oldVelocityX = ndx * oldVel;
float oldVelocityY = ndy * oldVel;
if (Math.signum(velocityX) == Math.signum(oldVelocityX)
&& Math.signum(velocityY) == Math.signum(oldVelocityY)) {
velocityX += oldVelocityX;
velocityY += oldVelocityY;
}
}
mMode = FLING_MODE;
mFinished = false;
float velocity = FloatMath.sqrt(velocityX * velocityX + velocityY * velocityY);
mVelocity = velocity;
final double l = Math.log(START_TENSION * velocity / ALPHA);
mDuration = (int) (1000.0 * Math.exp(l / (DECELERATION_RATE - 1.0)));
mStartTime = AnimationUtils.currentAnimationTimeMillis();
mStartX = startX;
mStartY = startY;
float coeffX = velocity == 0 ? 1.0f : velocityX / velocity;
float coeffY = velocity == 0 ? 1.0f : velocityY / velocity;
int totalDistance = (int) (ALPHA * Math.exp(DECELERATION_RATE / (DECELERATION_RATE - 1.0) * l));
mMinX = minX;
mMaxX = maxX;
mMinY = minY;
mMaxY = maxY;
mFinalX = startX + Math.round(totalDistance * coeffX);
mFinalX = Math.min(mFinalX, mMaxX);
mFinalX = Math.max(mFinalX, mMinX);
mFinalY = startY + Math.round(totalDistance * coeffY);
mFinalY = Math.min(mFinalY, mMaxY);
mFinalY = Math.max(mFinalY, mMinY);
}
這個方法對應 GestureDetector.OnGestureListener 的 onFling 概念,依滑動速率決定後續行為,主要處理慣性的座標變化,實務上使用頻率不高。
public void abortAnimation() {
mCurrX = mFinalX;
mCurrY = mFinalY;
mFinished = true;
}
看原始碼就知道,停止動畫只是把座標拉到終點、設一個完成旗標,之後就不再計算了。
static {
float x_min = 0.0f;
for (int i = 0; i <= NB_SAMPLES; i++) {
final float t = (float) i / NB_SAMPLES;
float x_max = 1.0f;
float x, tx, coef;
while (true) {
x = x_min + (x_max - x_min) / 2.0f;
coef = 3.0f * x * (1.0f - x);
tx = coef * ((1.0f - x) * START_TENSION + x * END_TENSION) + x * x * x;
if (Math.abs(tx - t) < 1E-5) break;
if (tx > t) x_max = x;
else x_min = x;
}
final float d = coef + x * x * x;
SPLINE[i] = d;
}
SPLINE[NB_SAMPLES] = 1.0f;
// This controls the viscous fluid effect (how much of it)
sViscousFluidScale = 8.0f;
// must be set to 1.0 (used in viscousFluid())
sViscousFluidNormalize = 1.0f;
sViscousFluidNormalize = 1.0f / viscousFluid(1.0f);
}
這段程式讓我卡了很久。我的理解是:它把慣性模式的位移比例切成 NB_SAMPLES 份,用二分法反解到 0.00001 的精度,填進 SPLINE 表;慣性滑動時只要拿目前時間比例查表,就能得到對應的座標位置。
說到底,Android 的動畫本質上就是對座標的精確計算。這裡只是最基礎的平滑滑動,有能力的人完全可以照自己的需求寫一套座標計算類,做出想要的動感。
Scroller 的實際用法這裡不再贅述,推薦一篇寫得很清楚的範例文章:https://ipjmc.iteye.com/blog/1615828,裡頭有完整的 demo 可以參考,歡迎留言討論。
第三方登入區塊的上拉展開、下拉隱藏:屬性動畫實作
UI 與交互直接決定了使用者對一款應用的第一印象,而動畫在其中扮演的角色越來越吃重。本文把專案登入頁中的一個小效果抽離出來:第三方登入區可上拉展開、下拉隱藏,讓畫面在安靜
Android 對稱加密與非對稱加密入門詳解
凱撒密碼1. 介紹凱撒密碼是最古老的對稱加密體制之一,在古羅馬時期就已流行。基本思想是透過把字母移動固定位數來實現加解密。例如偏移量為 3 時,A 變 D、B 變 E,而
Android 內建瀏覽器 Webkit 架構與 WebView 用法全解
一、Webkit 架構 1.1 簡介 Android 平台的 Webkit 模組可分為 Java 與 WebKit 庫兩大部分。 1.2 Webkit 目錄結構 根目錄:
自訂 IntroView 控件:重寫 onDraw 實現表情與超連結(一)
先來看看效果圖: 本文示範如何打造一個類似 TextView、同時能顯示表情圖示與可點擊超連結的自訂控件。首先定義一個用於承載超連結資訊的物件: /**作為超連接顯示的