編輯:關於 Android 程式設計
很久沒更新博客了,這次忙裡偷閒產出一篇。寫這篇文章主要是源於去年項目中的一個需求,當時三下五除二就把功能實現了,但源碼閱讀卻一直擱置著沒時間理會,現在正好撿起來看看,否則心裡總不踏實。
關於ViewDragHelper是什麼,官方註釋已經說得很到位了:
/**
* ViewDragHelper is a utility class for writing custom ViewGroups. It offers a number
* of useful operations and state tracking for allowing a user to drag and reposition
* views within their parent ViewGroup.
*/
下面我們先從一個例子說起,再進行源碼淺析。
在深入源碼之前,有必要先通過實例認識一下它的功效,下面的效果圖便是其中之一:

這個效果與去年那個項目的需求十分接近(出於保密做了些修改)。當時的需求大致是:能夠上下平滑收縮;能夠通過上下手勢收縮;能夠跟隨手指手勢按一定比例收縮;下層是ScrollView、上層是ListView的業務交互。
拿到需求時,我腦海裡萌生過三套方案:用屬性動畫、用滑動手勢、還是用ViewDragHelper。思考一番後我決定用ViewDragHelper,因為它實現起來相對簡單,其餘方案則麻煩不少。下面給出ViewDragHelper的實現代碼:
/**
* 垂直DrawerLayout
* 實現步驟:
* 1.使用靜態方法創建ViewDragHelper, 需要傳入一個ViewDragHelper.Callback對象.
* 2.重寫onInterceptTouchEvent和onTouchEvent回調ViewDragHelper中對應方法.
* 3.在ViewDragHelper.Callback中對視圖做操作.
* 4.使用ViewDragHelper.smoothSlideViewTo()方法平滑滾動.
* 5.自定義一些交互邏輯的自由實現.
*/
public class VerticalDrawerLayout extends ViewGroup {
private ViewDragHelper mTopViewDragHelper;
private View mContentView;
private View mDrawerView;
private int mCurTop = 0;
private boolean mIsOpen = true;
public VerticalDrawerLayout(Context context) { super(context); init(); }
public VerticalDrawerLayout(Context context, AttributeSet attrs) { super(context, attrs); init(); }
public VerticalDrawerLayout(Context context, AttributeSet attrs, int defStyleAttr) { super(context, attrs, defStyleAttr); init(); }
private void init() {
// Step1:使用靜態方法構造ViewDragHelper, 傳入一個Callback回調對象.
mTopViewDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragHelperCallBack());
mTopViewDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_TOP);
}
// Step2:定義一個ViewDragHelper.Callback回調實現類
private class ViewDragHelperCallBack extends ViewDragHelper.Callback {
@Override
public boolean tryCaptureView(View child, int pointerId) {
// 返回true則表示可以捕獲該view
return child == mDrawerView;
}
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId) {
// setEdgeTrackingEnabled設置的邊界滑動時觸發
// captureChildView是為了讓tryCaptureView返回false依舊生效
mTopViewDragHelper.captureChildView(mDrawerView, pointerId);
}
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
return super.clampViewPositionHorizontal(child, left, dx);
}
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
// 保證手指挪動時只能向上,向下最大到0
return Math.max(Math.min(top, 0), -mDrawerView.getHeight());
}
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
float movePrecent = (releasedChild.getHeight() + releasedChild.getTop()) / (float) releasedChild.getHeight();
int finalTop = (xvel >= 0 && movePrecent > 0.5f) ? 0 : -releasedChild.getHeight();
mTopViewDragHelper.settleCapturedViewAt(releasedChild.getLeft(), finalTop);
invalidate();
}
@Override
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {
// mDrawerView完全挪出屏幕則防止過度繪制
mDrawerView.setVisibility((changedView.getHeight() + top == 0) ? View.GONE : View.VISIBLE);
mCurTop = top;
requestLayout();
}
@Override
public int getViewVerticalDragRange(View child) {
if (mDrawerView == null) return 0;
return (mDrawerView == child) ? mDrawerView.getHeight() : 0;
}
@Override
public void onViewDragStateChanged(int state) {
super.onViewDragStateChanged(state);
if (state == ViewDragHelper.STATE_IDLE) {
mIsOpen = (mDrawerView.getTop() == 0);
}
}
}
@Override
public void computeScroll() {
if (mTopViewDragHelper.continueSettling(true)) {
invalidate();
}
}
public void closeDrawer() {
if (mIsOpen) {
mTopViewDragHelper.smoothSlideViewTo(mDrawerView, mDrawerView.getLeft(), -mDrawerView.getHeight());
invalidate();
}
}
public void openDrawer() {
if (!mIsOpen) {
mTopViewDragHelper.smoothSlideViewTo(mDrawerView, mDrawerView.getLeft(), 0);
invalidate();
}
}
public boolean isDrawerOpened() { return mIsOpen; }
// Step3:重寫onInterceptTouchEvent回調ViewDragHelper中對應的方法.
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mTopViewDragHelper.shouldInterceptTouchEvent(ev);
}
// Step3:重寫onTouchEvent回調ViewDragHelper中對應的方法.
@Override
public boolean onTouchEvent(MotionEvent event) {
mTopViewDragHelper.processTouchEvent(event);
return true;
}
@Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
int measureWidth = MeasureSpec.getSize(widthMeasureSpec);
int measureHeight = MeasureSpec.getSize(heightMeasureSpec);
setMeasuredDimension(measureWidth, measureHeight);
mContentView = getChildAt(0);
mDrawerView = getChildAt(1);
MarginLayoutParams params = (MarginLayoutParams) mContentView.getLayoutParams();
int childWidthMeasureSpec = MeasureSpec.makeMeasureSpec(
measureWidth - (params.leftMargin + params.rightMargin), MeasureSpec.EXACTLY);
int childHeightMeasureSpec = MeasureSpec.makeMeasureSpec(
measureHeight - (params.topMargin + params.bottomMargin), MeasureSpec.EXACTLY);
mContentView.measure(childWidthMeasureSpec, childHeightMeasureSpec);
mDrawerView.measure(widthMeasureSpec, heightMeasureSpec);
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (changed) {
MarginLayoutParams params = (MarginLayoutParams) mContentView.getLayoutParams();
mContentView.layout(params.leftMargin, params.topMargin,
mContentView.getMeasuredWidth() + params.leftMargin,
mContentView.getMeasuredHeight() + params.topMargin);
params = (MarginLayoutParams) mDrawerView.getLayoutParams();
mDrawerView.layout(params.leftMargin, mCurTop + params.topMargin,
mDrawerView.getMeasuredWidth() + params.leftMargin,
mCurTop + mDrawerView.getMeasuredHeight() + params.topMargin);
}
}
}
是不是挺簡單?效果有了,代碼也有了,ViewDragHelper也體驗過了,接下來就該靜下心來看源碼了。
從例子可知,使用ViewDragHelper的第一步是通過靜態工廠方法create獲取實例,因為它的構造方法是私有的。先來看這些工廠方法:
public class ViewDragHelper {
public static ViewDragHelper create(ViewGroup forParent, float sensitivity, Callback cb) {
final ViewDragHelper helper = create(forParent, cb);
helper.mTouchSlop = (int) (helper.mTouchSlop * (1 / sensitivity));
return helper;
}
public static ViewDragHelper create(ViewGroup forParent, Callback cb) {
return new ViewDragHelper(forParent.getContext(), forParent, cb);
}
}
可見三參數的create本質上仍調用兩參數的create。其中forParent一般是我們自定義的ViewGroup,cb是控制子View狀態的回調抽象類實現對象,sensitivity用來調節mTouchSlop(這個值越大,mTouchSlop越小,對滑動的檢測就越敏感)。再看構造函數:
private ViewDragHelper(Context context, ViewGroup forParent, Callback cb) {
...
mParentView = forParent;
mCallback = cb;
final ViewConfiguration vc = ViewConfiguration.get(context);
final float density = context.getResources().getDisplayMetrics().density;
mEdgeSize = (int) (EDGE_SIZE * density + 0.5f);
mTouchSlop = vc.getScaledTouchSlop(); // 默認為8
mMaxVelocity = vc.getScaledMaximumFlingVelocity();
mMinVelocity = vc.getScaledMinimumFlingVelocity();
mScroller = ScrollerCompat.create(context, sInterpolator);
}
構造函數主要是一些參數的實例化,最關鍵的是實例化了一個Scroller,並重寫了插值器:
private static final Interpolator sInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
回到實例部分,我們在拿到ViewDragHelper實例後,重寫了ViewGroup的onInterceptTouchEvent和onTouchEvent,在其中分別觸發shouldInterceptTouchEvent和processTouchEvent。先看shouldInterceptTouchEvent(以ACTION_DOWN為主線):
public boolean shouldInterceptTouchEvent(MotionEvent ev) {
final int action = MotionEventCompat.getActionMasked(ev);
final int actionIndex = MotionEventCompat.getActionIndex(ev);
if (action == MotionEvent.ACTION_DOWN) {
// 每次ACTION_DOWN都會調用cancel(), 清空mVelocityTracker
cancel();
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action) {
case MotionEvent.ACTION_DOWN: {
final float x = ev.getX();
final float y = ev.getY();
final int pointerId = MotionEventCompat.getPointerId(ev, 0);
// Step 1: 保存初始信息
saveInitialMotion(x, y, pointerId);
// Step 2: 找到當前觸摸點下最頂層的子View
final View toCapture = findTopChildUnder((int) x, (int) y);
// Step 3: 若已捕獲且處於settling狀態, 嘗試拖拽
if (toCapture == mCapturedView && mDragState == STATE_SETTLING) {
tryCaptureViewForDrag(toCapture, pointerId);
}
// Step 4: 邊沿觸摸回調
final int edgesTouched = mInitialEdgesTouched[pointerId];
if ((edgesTouched & mTrackingEdges) != 0) {
mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId);
}
break;
}
...
}
// Step 5: 只有拖動狀態才返回true
return mDragState == STATE_DRAGGING;
}
saveInitialMotion保存了事件的初始信息;findTopChildUnder則倒序遍歷子View,找到當前觸摸點下最頂層且可獲得焦點的那個:
public View findTopChildUnder(int x, int y) {
final int childCount = mParentView.getChildCount();
for (int i = childCount - 1; i >= 0; i--) {
final View child = mParentView.getChildAt(mCallback.getOrderedChildIndex(i));
if (x >= child.getLeft() && x < child.getRight()
&& y >= child.getTop() && y < child.getBottom()) {
return child;
}
}
return null;
}
注意這裡getChildAt傳入的是mCallback.getOrderedChildIndex(i),而Callback中該方法默認直接返回index。它的存在是為了應對一個場景:當同一位置有多個子View重疊時,若默認的倒序遍歷選不中你想要的那個(比如下層),就需要重寫getOrderedChildIndex來改變查找順序。
回到Step 4,第一次觸摸時mCapturedView為null、mDragState也不是STATE_SETTLING,所以Step 3不執行;Step 5返回mDragState == STATE_DRAGGING,此時仍是STATE_IDLE,故返回false。這意味著父容器沒有攔截這次事件,後續會分發給各子View的dispatchTouchEvent。
接下來看子View沒有消費這次ACTION_DOWN(dispatchTouchEvent返回false)的情況。此時父容器的onTouchEvent會被調用,也就是ViewDragHelper的processTouchEvent被執行。它的ACTION_DOWN核心在於tryCaptureViewForDrag:
boolean tryCaptureViewForDrag(View toCapture, int pointerId) {
if (toCapture == mCapturedView && mActivePointerId == pointerId) {
return true;
}
// 由Callback的tryCaptureView決定是否能拖動當前View
if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) {
mActivePointerId = pointerId;
captureChildView(toCapture, pointerId);
return true;
}
return false;
}
一旦允許拖動,便調用captureChildView暫存被捕獲的View並把狀態置為STATE_DRAGGING。
再來看主線的ACTION_MOVE。當可以拖拽時,會不斷調用dragTo對mCapturedView進行拖動:
private void dragTo(int left, int top, int dx, int dy) {
int clampedX = left;
int clampedY = top;
final int oldLeft = mCapturedView.getLeft();
final int oldTop = mCapturedView.getTop();
if (dx != 0) {
clampedX = mCallback.clampViewPositionHorizontal(mCapturedView, left, dx);
mCapturedView.offsetLeftAndRight(clampedX - oldLeft);
}
if (dy != 0) {
clampedY = mCallback.clampViewPositionVertical(mCapturedView, top, dy);
mCapturedView.offsetTopAndBottom(clampedY - oldTop);
}
if (dx != 0 || dy != 0) {
mCallback.onViewPositionChanged(mCapturedView, clampedX, clampedY, clampedX - oldLeft, clampedY - oldTop);
}
}
可以看到,View具體移動到哪、范圍多大,完全由Callback的clampViewPositionHorizontal與clampViewPositionVertical決定。若不能拖拽,則通過reportNewEdgeDrags回調onEdgeDragStarted,並用checkTouchSlop判斷手指移動是否超過了觸發閾值mTouchSlop:
private boolean checkTouchSlop(View child, float dx, float dy) {
if (child == null) {
return false;
}
final boolean checkHorizontal = mCallback.getViewHorizontalDragRange(child) > 0;
final boolean checkVertical = mCallback.getViewVerticalDragRange(child) > 0;
if (checkHorizontal && checkVertical) {
return dx * dx + dy * dy > mTouchSlop * mTouchSlop;
} else if (checkHorizontal) {
return Math.abs(dx) > mTouchSlop;
} else if (checkVertical) {
return Math.abs(dy) > mTouchSlop;
}
return false;
}
最後是松手時的ACTION_UP或ACTION_CANCEL。二者本質相同,都是重置資源並通知View被釋放,只是ACTION_UP會先計算松手前各方向的速率:
private void releaseViewForPointerUp() {
mVelocityTracker.computeCurrentVelocity(1000, mMaxVelocity);
final float xvel = clampMag(VelocityTrackerCompat.getXVelocity(mVelocityTracker, mActivePointerId), mMinVelocity, mMaxVelocity);
final float yvel = clampMag(VelocityTrackerCompat.getYVelocity(mVelocityTracker, mActivePointerId), mMinVelocity, mMaxVelocity);
dispatchViewReleased(xvel, yvel);
}
private void dispatchViewReleased(float xvel, float yvel) {
mReleaseInProgress = true;
mCallback.onViewReleased(mCapturedView, xvel, yvel);
mReleaseInProgress = false;
if (mDragState == STATE_DRAGGING) {
setDragState(STATE_IDLE);
}
}
這裡有個值得玩味的細節:settleCapturedViewAt與flingCapturedView開頭都會判斷if (!mReleaseInProgress)並拋出IllegalStateException,也就是說這兩個方法只能在Callback的onViewReleased裡調用。原因就是mReleaseInProgress默認為false,只有在dispatchViewReleased回調onViewReleased前後才被置為true。而smoothSlideViewTo則不受此限制,它同樣能實現平滑滾動到指定位置,可在任何地方調用。
梳理下ViewDragHelper的常用核心API:
public class ViewDragHelper {
public static final int STATE_IDLE = 0; // 空閒靜止
public static final int STATE_DRAGGING = 1; // 拖動中
public static final int STATE_SETTLING = 2; // 慣性滾動到目標位置中
public static final int EDGE_LEFT = 1 << 0;
public static final int EDGE_RIGHT = 1 << 1;
public static final int EDGE_TOP = 1 << 2;
public static final int EDGE_BOTTOM = 1 << 3;
public static final int EDGE_ALL = EDGE_LEFT | EDGE_TOP | EDGE_RIGHT | EDGE_BOTTOM;
public static abstract class Callback {
public void onViewDragStateChanged(int state) {}
public void onViewPositionChanged(View changedView, int left, int top, int dx, int dy) {}
public void onViewCaptured(View capturedChild, int activePointerId) {}
public void onViewReleased(View releasedChild, float xvel, float yvel) {}
public void onEdgeTouched(int edgeFlags, int pointerId) {}
public boolean onEdgeLock(int edgeFlags) { return false; }
public void onEdgeDragStarted(int edgeFlags, int pointerId) {}
public int getOrderedChildIndex(int index) { return index; }
public int getViewHorizontalDragRange(View child) { return 0; }
public int getViewVerticalDragRange(View child) { return 0; }
public abstract boolean tryCaptureView(View child, int pointerId);
public int clampViewPositionHorizontal(View child, int left, int dx) { return 0; }
public int clampViewPositionVertical(View child, int top, int dy) { return 0; }
}
// 構造工廠方法
public static ViewDragHelper create(ViewGroup forParent, float sensitivity, Callback cb) {...}
public void setEdgeTrackingEnabled(int edgeFlags) {...}
public boolean shouldInterceptTouchEvent(MotionEvent ev) {...}
public void processTouchEvent(MotionEvent ev) {...}
public void captureChildView(View childView, int activePointerId) {...}
public boolean smoothSlideViewTo(View child, int finalLeft, int finalTop) {...}
public boolean settleCapturedViewAt(int finalLeft, int finalTop) {...} // 僅能在onViewReleased中調用
public void flingCapturedView(int minLeft, int minTop, int maxLeft, int maxTop) {...} // 僅能在onViewReleased中調用
public boolean continueSettling(boolean deferCallbacks) {...}
public int getViewDragState() {...}
public View getCapturedView() {...}
public int getTouchSlop() {...}
public void cancel() {...}
public void abort() {...}
}
有了這些API的組合,我們基本能搗鼓出各種自定義控件。使用流程可歸納為:
1、自定義ViewGroup中通過create()創建實例並實現Callback抽象類。
2、在onInterceptTouchEvent中調用並返回shouldInterceptTouchEvent,在onTouchEvent中調用processTouchEvent並返回true(否則ACTION_DOWN後收不到後續事件,也就無法拖動)。
3、按需實現Callback中的相關方法。
4、若需要Fling或慣性滾動效果,還需實現computeScroll()手動刷幀:
@Override
public void computeScroll() {
if (mDragHelper.continueSettling(true)) {
ViewCompat.postInvalidateOnAnimation(this);
}
}
最後給出一個用ViewDragHelper搗鼓出來的控件效果(GIF在Ubuntu下畫質較Low,敬請諒解):

至此整個ViewDragHelper的進階就介紹完了。如果你還覺得不夠,不妨去研究官方的DrawerLayout,把它當作本文的進階實例(我們項目中因特殊交互需求重寫了DrawerLayout)。總的來說,ViewDragHelper封裝了大量複雜的觸摸事件處理細節,是一個相當強大的工具類。
Android 路徑動畫:用 PathMeasure 讓物件沿曲線飛行
前言 專案裡要做一個類似「發送表情從螢幕下方飄出」的效果,本質上就是路徑動畫:先畫出一條路徑,再讓物件沿著這條路徑移動。 要解決的問題其實只有兩個:怎麼畫出路徑?以及怎麼
Android 6.0(API 23)行為變更總整理:升級前必讀
伴隨著新功能與新能力,Android 6.0(API level 23)也帶來了大量系統與 API 行為上的變化。本文整理其中幾項最容易被忽略、卻會直接影響既有應用的變更
Android 資料儲存(三):SQLite 資料庫儲存完整指南
SQLite 是 Android 系統內建的資料庫,屬於輕量級關聯式資料庫。它運算速度快、佔用資源少,非常適合行動裝置;不僅支援標準 SQL 語法,也遵循資料庫的 ACI
Android Studio 小技巧:自訂 logcat 各等級的顯示顏色
Android Studio 預設的 logcat 顯示顏色是灰色的,不同等級的 log 幾乎沒有顏色區分,如下圖: 這一點確實不如 Eclipse 來得清楚。但其實