編輯:關於 Android 開發
做自訂 ViewGroup 時,「讓子 View 能被手指拖動」幾乎是必經關卡。自己處理 MotionEvent、 VelocityTracker、Scroller 與邊緣判斷,程式碼會迅速膨脹且容易出錯。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. */
先看效果,一個能上下收放、跟手拖曳並帶慣性的頂層面板:
使用 ViewDragHelper 的標準五步:
create() 取得實例,並傳入一個 ViewDragHelper.Callback。onInterceptTouchEvent 與 onTouchEvent,分別轉呼叫 shouldInterceptTouchEvent 與 processTouchEvent。smoothSlideViewTo() 觸發平滑滾動,並在 computeScroll() 中持續刷幀。public class VerticalDrawerLayout extends ViewGroup {
private ViewDragHelper mTopViewDragHelper;
private View mContentView;
private View mDrawerView;
private int mCurTop = 0;
private boolean mIsOpen = true;
private void init() {
// Step1:建立 ViewDragHelper,sensitivity 傳 1.0f 即可
mTopViewDragHelper = ViewDragHelper.create(this, 1.0f, new ViewDragHelperCallBack());
mTopViewDragHelper.setEdgeTrackingEnabled(ViewDragHelper.EDGE_TOP);
}
// Step3:Callback 決定拖曳行為
private class ViewDragHelperCallBack extends ViewDragHelper.Callback {
@Override
public boolean tryCaptureView(View child, int pointerId) {
return child == mDrawerView; // 只有抽屜 View 可拖
}
@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 = (yvel >= 0 && movePrecent > 0.5f) ? 0 : -releasedChild.getHeight();
mTopViewDragHelper.settleCapturedViewAt(releasedChild.getLeft(), finalTop);
invalidate();
}
@Override
public int getViewVerticalDragRange(View child) {
return (mDrawerView == child) ? mDrawerView.getHeight() : 0;
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return mTopViewDragHelper.shouldInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
mTopViewDragHelper.processTouchEvent(event);
return true;
}
@Override
public void computeScroll() {
if (mTopViewDragHelper.continueSettling(true)) {
invalidate();
}
}
}
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);
}
三參數版本實際只是拿二參數版本再縮放 mTouchSlop。sensitivity 越大,mTouchSlop 越小,代表手指移動更少就被判定為拖曳,靈敏度更高。
建構子主要在做參數初始化:透過 ViewConfiguration 取得 mTouchSlop(預設約 8dp)、最大/最小 fling 速度,並建立 ScrollerCompat,同時覆寫了一個五次方曲線的插值器:
private static final Interpolator sInterpolator = new Interpolator() {
public float getInterpolation(float t) {
t -= 1.0f;
return t * t * t * t * t + 1.0f;
}
};
public boolean shouldInterceptTouchEvent(MotionEvent ev) {
...
if (action == MotionEvent.ACTION_DOWN) {
cancel(); // 每次 DOWN 都重置並清空 VelocityTracker
}
if (mVelocityTracker == null) {
mVelocityTracker = VelocityTracker.obtain();
}
mVelocityTracker.addMovement(ev);
switch (action) {
case MotionEvent.ACTION_DOWN:
saveInitialMotion(x, y, pointerId); // Step1 記錄初始位置與邊緣
final View toCapture = findTopChildUnder((int) x, (int) y); // Step2 找最上層子 View
...
final int edgesTouched = mInitialEdgesTouched[pointerId];
if ((edgesTouched & mTrackingEdges) != 0) {
mCallback.onEdgeTouched(edgesTouched & mTrackingEdges, pointerId); // Step4
}
break;
}
return mDragState == STATE_DRAGGING; // Step5:DOWN 時仍為 STATE_IDLE,回傳 false
}
第一次按下時 mDragState 還是 STATE_IDLE,所以回傳 false,事件會繼續往下傳給子 View。
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;
}
這裡傳入的是 mCallback.getOrderedChildIndex(i) 而非 i,預設實作直接回傳 index。它存在的意義是:當多個子 View 在同一位置重疊時,你可以覆寫此方法,指定讓下層的 View 優先被選中。
boolean tryCaptureViewForDrag(View toCapture, int pointerId) {
if (toCapture == mCapturedView && mActivePointerId == pointerId) return true;
if (toCapture != null && mCallback.tryCaptureView(toCapture, pointerId)) {
mActivePointerId = pointerId;
captureChildView(toCapture, pointerId);
return true;
}
return false;
}
public void captureChildView(View childView, int activePointerId) {
mCapturedView = childView;
mActivePointerId = activePointerId;
mCallback.onViewCaptured(childView, activePointerId);
setDragState(STATE_DRAGGING);
}
也就是說,tryCaptureView() 回傳 true 是拖曳啟動的關鍵;若你需要「邊緣手勢直接抓起某個摸不到的 View」,可在 onEdgeDragStarted() 中手動呼叫 captureChildView() 繞過它。
若已進入 STATE_DRAGGING,每次 MOVE 就計算位移並呼叫 dragTo();否則逐一手指定義判斷是否該開始拖曳:
private void dragTo(int left, int top, int dx, int dy) {
int clampedX = left, 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);
}
}
移動到哪、能移多遠,完全由 clampViewPositionHorizontal() 與 clampViewPositionVertical() 決定——若想讓某方向完全不動,固定回傳 0 即可。而 checkTouchSlop() 則依 getViewHorizontalDragRange()/getViewVerticalDragRange() 是否大於 0,判斷該方向是否允許拖曳。
private void dispatchViewReleased(float xvel, float yvel) {
mReleaseInProgress = true;
mCallback.onViewReleased(mCapturedView, xvel, yvel);
mReleaseInProgress = false;
if (mDragState == STATE_DRAGGING) setDragState(STATE_IDLE);
}
ACTION_UP 與 ACTION_CANCEL 邏輯一致,差別只在傳入的速度:UP 會用 VelocityTracker 算出實際速度,CANCEL 則傳 0。
而 settleCapturedViewAt() 與 flingCapturedView() 開頭都有這段檢查:
if (!mReleaseInProgress) {
throw new IllegalStateException("Cannot settleCapturedViewAt outside of a call to "
+ "Callback#onViewReleased");
}
由於 mReleaseInProgress 只在 dispatchViewReleased() 回呼 onViewReleased() 期間為 true,因此這兩個 API 只能在 Callback.onViewReleased() 中呼叫,其他位置會直接拋例外。若要在別處觸發平滑移動,請改用 smoothSlideViewTo()。
STATE_IDLE(靜止)、STATE_DRAGGING(拖動中)、STATE_SETTLING(慣性滾動中)EDGE_LEFT / EDGE_RIGHT / EDGE_TOP / EDGE_BOTTOM / EDGE_ALLtryCaptureView()(能否拖)、clampViewPositionVertical/Horizontal()(可拖範圍)、onViewReleased()(放開後去向)、onViewPositionChanged()(位置變化)、getViewVerticalDragRange()(該方向是否可拖)、onEdgeDragStarted()(邊緣手勢)、getOrderedChildIndex()(重疊順序)setEdgeTrackingEnabled()、shouldInterceptTouchEvent()、processTouchEvent()、captureChildView()、smoothSlideViewTo()、continueSettling()、getCapturedView()、getViewDragState()、cancel()、abort()create() 建立實例,並實作 Callback。onInterceptTouchEvent() 回傳 shouldInterceptTouchEvent();於 onTouchEvent() 呼叫 processTouchEvent() 並回傳 true(否則收不到後續 MOVE 事件)。computeScroll() 並在其中呼叫 continueSettling(true) 搭配 postInvalidateOnAnimation() 持續刷幀。
掌握主流程後,再回頭對照官方 DrawerLayout 的實作會非常有收穫——它基本上就是 ViewDragHelper 的進階範例。
模擬微信聊天菜單:OptionsMenu 與 ContextMenu 的配合使用
在微信裡長按一條聊天記錄,會從底部彈出「標記為未讀 / 置頂聊天 / 刪除該聊天」的浮層。這個交互在原生 Android 中,可以用 OptionsMenu 與 Cont
用 TextView 顯示 HTML 樣式文字:Html.fromHtml 方法實戰
有時候我們需要在一個 TextView 中讓不同部分的文字呈現不同的顏色和字號,例如「白雪公主向您發來了 2 條消息」這樣的提示,其中姓名和數字長度不固定,還要求各自有不
Redmine 整合 LDAP 認證:從 LDIF 資料準備到後台設定完整流程
Redmine 整合 LDAP 認證:從 LDIF 資料準備到後台設定完整流程 要把 Redmine 與 LDAP 帳號整合,第一步當然是先把 LDAP 環境設定好,否則
ImageLoader 使用指南:Android 圖片加載與快取設定
ImageLoader 使用指南:Android 圖片加載與快取設定 Universal Image Loader 是早期 Android 常見的圖片加載框架,適合需要自