編輯:關於 Android 程式設計
Launcher 是 Android 上最容易被忽略、卻又最常被拿來改造的模組。本文以 Android 4.4 的 Launcher3 為例,從 WorkSpace 這個核心容器切入,一路追到桌面左右滑動的實作細節,並示範幾個可以直接改的參數。
前面已經介紹過,一個 WorkSpace 裡含多個 CellLayout。回顧一下整體結構:

WorkSpace 本身就是一個 ViewGroup,它的版面配置相當簡潔:
<com.android.launcher3.Workspace
android:id="@+id/workspace"
android:layout_width="match_parent"
android:layout_height="match_parent"
launcher:defaultScreen="@integer/config_workspaceDefaultScreen"
launcher:pageIndicator="@id/page_indicator"
launcher:pageSpacing="@dimen/workspace_page_spacing" />
三個自訂屬性分別是:defaultScreen 為預設桌面序號、pageIndicator 為頁面指示器、pageSpacing 為頁面間距。

它繼承自 SmoothPagedView(最終源頭是 PagedView),同時實作了一堆與拖放相關的介面:
public class Workspace extends SmoothPagedView
implements DropTarget, DragSource, DragScroller,
View.OnTouchListener, DragController.DragListener,
LauncherTransitionable, ViewGroup.OnHierarchyChangeListener,
Insettable {
public Workspace(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
mContentIsRefreshable = false;
mOutlineHelper = HolographicOutlineHelper.obtain(context);
mDragEnforcer = new DropTarget.DragEnforcer(context);
setDataIsReady();
mLauncher = (Launcher) context;
final Resources res = getResources();
mWorkspaceFadeInAdjacentScreens =
res.getBoolean(R.bool.config_workspaceFadeAdjacentScreens);
mFadeInAdjacentScreens = false;
mWallpaperManager = WallpaperManager.getInstance(context);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.Workspace, defStyle, 0);
// 在 all apps 列表中長按 item 時,workspace 的縮放比例
mSpringLoadedShrinkFactor =
res.getInteger(R.integer.config_workspaceSpringLoadShrinkPercentage) / 100.0f;
// 可滑動區域的縮放比例
mOverviewModeShrinkFactor =
res.getInteger(R.integer.config_workspaceOverviewShrinkPercentage) / 100.0f;
mOverviewModePageOffset = res.getDimensionPixelSize(R.dimen.overview_mode_page_offset);
// 滑到邊緣無法再滑動時,拖動的 Z 軸距離(決定 3D 景深強度)
mCameraDistance = res.getInteger(R.integer.config_cameraDistance);
// 開機時的預設桌面
mOriginalDefaultPage = mDefaultPage = a.getInt(R.styleable.Workspace_defaultScreen, 1);
a.recycle();
setOnHierarchyChangeListener(this);
setHapticFeedbackEnabled(false);
initWorkspace();
setMotionEventSplittingEnabled(true);
setImportantForAccessibility(View.IMPORTANT_FOR_ACCESSIBILITY_YES);
}
mSpringLoadedShrinkFactor 是在「所有應用」列表中長按項目時,桌面的縮略比例,預設 0.8。我把它改成 0.01,桌面幾乎縮到看不見:

mOverviewModeShrinkFactor 則是可滑動區域的縮放比例,預設 0.58。如果把項目拖出這個區域,刪除框就會出現。我把它改成 4,行為立刻變得完全不同:

mCameraDistance 是滑到邊緣無法再滑動時,拖動造成的 Z 軸位移,也就是那種 3D 景深效果,預設 8000。改成 1000 之後,景深壓縮感明顯增強:

protected void initWorkspace() {
Context context = getContext();
mCurrentPage = mDefaultPage; // 當前頁設為預設頁
Launcher.setScreen(mCurrentPage);
LauncherAppState app = LauncherAppState.getInstance();
DeviceProfile grid = app.getDynamicGrid().getDeviceProfile();
mIconCache = app.getIconCache();
setWillNotDraw(false);
setClipChildren(false);
setClipToPadding(false);
setChildrenDrawnWithCacheEnabled(true);
// 因為 workspace 整體上移了一點,這裡要預留背景繪製空間
setMinScale(mOverviewModeShrinkFactor - 0.2f);
setupLayoutTransition();
final Resources res = getResources();
try {
mBackground = res.getDrawable(R.drawable.apps_customize_bg);
} catch (Resources.NotFoundException e) {
// 找不到就跳過背景保護
}
mWallpaperOffset = new WallpaperOffsetInterpolator();
Display display = mLauncher.getWindowManager().getDefaultDisplay();
display.getSize(mDisplaySize);
mMaxDistanceForFolderCreation = (0.55f * grid.iconSizePx);
mFlingThresholdVelocity = (int) (FLING_THRESHOLD_VELOCITY * mDensity);
}
把 mBackground 換成自備的圖片資源,桌面縮略圖的背景就會跟著改變:

WorkSpace 同時實作了 DragSource 與 DropTarget,也就是說它既是拖曳的來源,也是放置的容器。
void startDrag(CellLayout.CellInfo cellInfo) {
View child = cellInfo.cell;
// 確認是由長按觸發,而非長按點擊
if (!child.isInTouchMode()) {
return;
}
mDragInfo = cellInfo;
child.setVisibility(INVISIBLE); // 原位置的 item 設為不可見
CellLayout layout = (CellLayout) child.getParent().getParent();
layout.prepareChildForDrag(child);
child.clearFocus();
child.setPressed(false);
final Canvas canvas = new Canvas();
// item 拖動時跟著移動的浮層圖
mDragOutline = createDragOutline(child, canvas, DRAG_BITMAP_PADDING);
beginDragShared(child, this);
}
把 setVisibility(INVISIBLE) 拿掉、再把 mDragOutline 換成自訂的圖片,就會得到一個「原圖標還留在桌上、拖動時另外跟著一張圖」的怪表情景:

@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction() & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_DOWN:
mXDown = ev.getX();
mYDown = ev.getY();
mTouchDownTime = System.currentTimeMillis();
break;
case MotionEvent.ACTION_POINTER_UP:
case MotionEvent.ACTION_UP:
if (mTouchState == TOUCH_STATE_REST) {
final CellLayout currentPage = (CellLayout) getChildAt(mCurrentPage);
if (!currentPage.lastDownOnOccupiedCell()) {
onWallpaperTap(ev); // 點空白處換壁紙
}
}
}
return super.onInterceptTouchEvent(ev); // 交給 PagedView 處理
}
WorkSpace 自己只記錄按下的座標與時間,真正的攔截判斷丟給父類別 PagedView。
@Override
public boolean onTouch(View v, MotionEvent event) {
return (isSmall() || !isFinishedSwitchingState())
|| (!isSmall() && indexOfChild(v) != mCurrentPage);
}
當桌面進入縮略圖狀態,或狀態切換尚未完成時回傳 true;此外非縮略圖狀態下,若觸摸的頁面不是當前頁,也會回傳 true 由自己處理。
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
if (mFirstLayout && mCurrentPage >= 0 && mCurrentPage < getChildCount()) {
mWallpaperOffset.syncWithScroll();
mWallpaperOffset.jumpToFinal();
}
super.onLayout(changed, left, top, right, bottom);
}
首次排版且位於有效頁時,會同步一次壁紙偏移量。mWallpaperOffset 是 WallpaperOffsetInterpolator 的執行個體,它實作了 Choreographer.FrameCallback,負責在 UI 繪製流程中更新壁紙位置。
public void syncWithScroll() {
float offset = wallpaperOffsetForCurrentScroll(); // 取得目前滾動對應的偏移
mWallpaperOffset.setFinalX(offset);
updateOffset(true);
}
public void jumpToFinal() {
mCurrentOffset = mFinalOffset; // 把最終偏移直接設為當前值
}
滑動邏輯並不在 WorkSpace,而是在它的父類別 PagedView。WorkSpace 的 onInterceptTouchEvent 最後呼叫了 super,這就是分析的起點。
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
if (DISABLE_TOUCH_INTERACTION) {
return false;
}
// 取得速度追蹤器並加入本次事件
acquireVelocityTrackerAndAddMovement(ev);
if (getChildCount() <= 0) return super.onInterceptTouchEvent(ev);
final int action = ev.getAction();
// 最常見的攔截情況:已進入滑動狀態且手指正在移動
if ((action == MotionEvent.ACTION_MOVE) && (mTouchState == TOUCH_STATE_SCROLLING)) {
return true;
}
switch (action & MotionEvent.ACTION_MASK) {
case MotionEvent.ACTION_MOVE:
if (mActivePointerId != INVALID_POINTER) {
determineScrollingStart(ev); // 判斷位移是否足夠
}
break;
case MotionEvent.ACTION_DOWN:
final float x = ev.getX();
final float y = ev.getY();
mDownMotionX = x;
mDownMotionY = y;
mDownScrollX = getScrollX();
mLastMotionX = x;
mLastMotionY = y;
float[] p = mapPointFromViewToParent(this, x, y);
mParentDownMotionX = p[0];
mParentDownMotionY = p[1];
mLastMotionXRemainder = 0;
mTotalMotionX = 0;
mActivePointerId = ev.getPointerId(0);
final int xDist = Math.abs(mScroller.getFinalX() - mScroller.getCurrX());
final boolean finishedScrolling = (mScroller.isFinished() || xDist < mTouchSlop);
if (finishedScrolling) {
mTouchState = TOUCH_STATE_REST;
mScroller.abortAnimation();
} else {
mTouchState = isTouchPointInViewportWithBuffer((int) mDownMotionX, (int) mDownMotionY)
? TOUCH_STATE_SCROLLING : TOUCH_STATE_REST;
}
// 左右邊緣可直接翻頁
if (!DISABLE_TOUCH_SIDE_PAGES) {
if (mTouchState != TOUCH_STATE_PREV_PAGE && mTouchState != TOUCH_STATE_NEXT_PAGE) {
if (getChildCount() > 0) {
if (hitsPreviousPage(x, y)) {
mTouchState = TOUCH_STATE_PREV_PAGE;
} else if (hitsNextPage(x, y)) {
mTouchState = TOUCH_STATE_NEXT_PAGE;
}
}
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
resetTouchState();
break;
case MotionEvent.ACTION_POINTER_UP:
onSecondaryPointerUp(ev);
releaseVelocityTracker();
break;
}
return mTouchState != TOUCH_STATE_REST;
}
最後一行是重點:只要 mTouchState 不是靜止狀態,就攔截事件交給 onTouchEvent。桌面狀態共有五種:
/** 滑動結束(靜止) */ protected final static int TOUCH_STATE_REST = 0; /** 正在滑動 */ protected final static int TOUCH_STATE_SCROLLING = 1; /** 滑動到上一頁 */ protected final static int TOUCH_STATE_PREV_PAGE = 2; /** 滑動到下一頁 */ protected final static int TOUCH_STATE_NEXT_PAGE = 3; /** 拖曳重排序 */ protected final static int TOUCH_STATE_REORDERING = 4;
protected void determineScrollingStart(MotionEvent ev, float touchSlopScale) {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
if (pointerIndex == -1) return;
final float x = ev.getX(pointerIndex);
final float y = ev.getY(pointerIndex);
// 手勢若從視窗外開始,則不處理
if (!isTouchPointInViewportWithBuffer((int) x, (int) y)) return;
final int xDiff = (int) Math.abs(x - mLastMotionX);
final int yDiff = (int) Math.abs(y - mLastMotionY);
final int touchSlop = Math.round(touchSlopScale * mTouchSlop);
boolean xPaged = xDiff > mPagingTouchSlop;
boolean xMoved = xDiff > touchSlop;
boolean yMoved = yDiff > touchSlop;
if (xMoved || xPaged || yMoved) {
if (mUsePagingTouchSlop ? xPaged : xMoved) {
mTouchState = TOUCH_STATE_SCROLLING;
mTotalMotionX += Math.abs(mLastMotionX - x);
mLastMotionX = x;
mLastMotionXRemainder = 0;
mTouchX = getViewportOffsetX() + getScrollX();
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
pageBeginMoving();
}
}
}
位移超過門檻就把狀態切成 SCROLLING,接著呼叫 pageBeginMoving();後者會再呼叫 onPageBeginMoving(),這是留給子類別覆寫的空方法。
case MotionEvent.ACTION_MOVE:
if (mTouchState == TOUCH_STATE_SCROLLING) {
final int pointerIndex = ev.findPointerIndex(mActivePointerId);
if (pointerIndex == -1) return true;
final float x = ev.getX(pointerIndex);
final float deltaX = mLastMotionX + mLastMotionXRemainder - x;
mTotalMotionX += Math.abs(deltaX);
// 只有位移達 1px 以上才真的滾動,餘數留給下一輪累積
if (Math.abs(deltaX) >= 1.0f) {
mTouchX += deltaX;
mSmoothingTime = System.nanoTime() / NANOTIME_DIV;
if (!mDeferScrollUpdate) {
scrollBy((int) deltaX, 0);
} else {
invalidate();
}
mLastMotionX = x;
mLastMotionXRemainder = deltaX - (int) deltaX;
} else {
awakenScrollBars();
}
} else if (mTouchState == TOUCH_STATE_REORDERING) {
// 拖曳重排序:更新座標、判斷是否懸停於刪除區或另一頁之上
// ……省略重排序的懸停與 ReorderRunnable 邏輯
} else {
determineScrollingStart(ev);
}
break;
這裡有個常被忽略的細節:mLastMotionXRemainder 保留小數餘數。因為 scrollBy() 只吃整數,若不把不足 1px 的部分留到下一輪,慢速滑動時會產生卡頓感。
滑動過程中會反覆呼叫 snapToPage(),這個方法有多重重載,最終都會收斂到:
protected void snapToPage(int whichPage, int delta, int duration, boolean immediate) {
mNextPage = whichPage;
View focusedChild = getFocusedChild();
if (focusedChild != null && whichPage != mCurrentPage
&& focusedChild == getPageAt(mCurrentPage)) {
focusedChild.clearFocus();
}
sendScrollAccessibilityEvent();
pageBeginMoving();
awakenScrollBars(duration);
if (immediate) {
duration = 0;
} else if (duration == 0) {
duration = Math.abs(delta);
}
if (!mScroller.isFinished()) {
mScroller.abortAnimation();
}
mScroller.startScroll(mUnboundedScrollX, 0, delta, 0, duration);
notifyPageSwitchListener();
if (immediate) {
computeScroll();
}
mDeferLoadAssociatedPagesUntilScrollCompletes = true;
mForceScreenScrolled = true;
invalidate();
}
把 duration 從預設值改成 9000,翻頁就會變成一個極慢的動畫,很適合用來觀察整個插值過程:

WorkSpace 本身幾乎不處理滑動,它只負責桌面特有的行為(點空白換壁紙、拖放、縮略圖狀態),滑動則完全交給 PagedView。這種分工讓 Launcher 的多頁邏輯得以被其他頁面型態共用。
另外,改 Launcher 參數時建議優先動 res/values/integers.xml 與 dimens 裡的資源值,而不是直接改 Java 常數——前者改完不必動邏輯,也比較容易還原。
歡迎留言交流。
Android 自定義圖片選擇元件:相冊、拍照、裁剪與刪除動畫
元件目標 本文實作一個類似社群貼文選圖的自定義元件,支援從相冊選擇圖片、拍照取得圖片、長按顯示刪除按鈕、動畫提示,以及達到數量上限後隱藏新增按鈕。 加號圖片永遠在最
OpenCV 常用基本數據結構梳理與示例
Mat 大概是人們對 OpenCV 最熟悉的類型,但工程中真正高頻出現的還有幾個更輕量的結構。這裡把它們集中梳理一遍: Vec、Scalar、Point、Size、Rec
Android 實現類似支付寶餘額快速跳動的數字動畫效果
此圖為靜態截圖,實際執行時數字會快速跳動。 之前看到支付寶的這個效果覺得非常帥:進入頁面時餘額會呼嚕嚕地從小數字一路竄升到最終金額,很有質感。但一直不知道怎麼實作,最近
Dagger2 依賴注入圖文全解:從入門到進階的完整教程
Dagger2 依賴注入圖文全解 廢話不多說,直接談談我對它的理解。Dagger2 是 Android 平台上相當知名的依賴注入框架。在當前 Android 開發中,M