編輯:關於 Android 程式設計
專案需要讓列表條目左滑時露出「收藏」按鈕。原本打算直接採用成熟開源庫 AndroidSwipeLayout,但翻過 issue 後發現累積了不少未修的問題,作者似乎也已停止維護。既然只需要一個精簡的效果,索然自己動手做一個。
因為目標明確,程式碼裡難免有些地方寫死(例如底層菜單寬度直接取實測值、閾值用比例硬編)。如果你需要的是大而全的功能,仍建議回到開源庫;若只需要「左滑露出操作區」,這份實作足夠且更好懂。
核心用到的 API 是 ViewDragHelper——它是 Support Library 提供的拖拽輔助類,幫你處理了手勢判定、邊界裁剪與拋擲(fling)等麻煩細節,比手寫 onTouchEvent 省事很多。
SwipeLayout 繼承 FrameLayout,內部固定兩個子 View:
mBottomView:底層菜單,先被排版在右側畫面之外。mTopView:上層內容(例如列表項本體),可左右拖動。建構子中建立 ViewDragHelper,並透過 Callback 定義拖拽規則;onLayout 負責把底層菜單藏到右側;onInterceptTouchEvent 與 onTouchEvent 把事件交給 helper 處理。
public class SwipeLayout extends FrameLayout {
public static final int CLOSE = 0;
public static final int OPEN = 1;
private int mState = CLOSE;
private int mWidth;
private int mHeight;
private float mDownX;
private float mDownY;
private SwipeListener mSwipeListener;
private View mTopView;
private View mBottomView;
private ViewDragHelper mViewDragHelper;
public SwipeLayout(Context context) {
this(context, null);
}
public SwipeLayout(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SwipeLayout(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mViewDragHelper = ViewDragHelper.create(this, new ViewDragHelper.Callback() {
/** 只處理 mTopView 的拖拽 */
@Override
public boolean tryCaptureView(View child, int pointerId) {
return child == mTopView;
}
/**
* 設定橫向拖動的邊界
* @param left mTopView 左上角目前的 x 座標
* @param dx 手指移動的距離
*/
@Override
public int clampViewPositionHorizontal(View child, int left, int dx) {
int newLeft;
if (left <= -mBottomView.getMeasuredWidth()) {
newLeft = -mBottomView.getMeasuredWidth(); // 完全展開
} else if (left >= 0) {
newLeft = 0; // 完全收起
} else {
newLeft = left;
}
return newLeft;
}
/** 不需要上下拖動,固定為 0 */
@Override
public int clampViewPositionVertical(View child, int top, int dy) {
return 0;
}
/** 手指鬆開時的回調,決定吸附到哪一側 */
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel) {
// mTopView 右邊界距離螢幕右側的距離
int right = mWidth - releasedChild.getRight();
int bottomWidth = mBottomView.getMeasuredWidth();
// 幾乎沒拉開:直接收回
if (right > bottomWidth * 9 / 10) {
scrollToLeftEdge();
return;
}
// 幾乎全開:直接展開
if (right <= bottomWidth / 10 && right > 0) {
scrollToRightEdge();
return;
}
// 速度為 0(等於沒有拋擲)時,改用位置比例判斷
if (xvel == 0) {
if (right >= bottomWidth / 2) {
scrollToLeftEdge();
} else {
scrollToRightEdge();
}
return;
}
// 有速度時以方向為準
if (xvel > 0) {
scrollToRightEdge(); // 向右滑動後鬆手 → 收起
} else {
scrollToLeftEdge(); // 向左滑動後鬆手 → 展開
}
}
});
}
/** 讓吸附動畫持續播放 */
@Override
public void computeScroll() {
if (mViewDragHelper.continueSettling(true)) {
invalidate();
}
}
@Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = ev.getRawX();
mDownY = ev.getRawY();
if (mState == CLOSE) {
return true; // 收起狀態下直接攔截,方便立刻起手
}
break;
case MotionEvent.ACTION_MOVE:
float distanceX = ev.getRawX() - mDownX;
float distanceY = ev.getRawY() - mDownY;
float angle;
if (distanceX == 0) {
angle = 90;
} else {
angle = (float) Math.toDegrees(
Math.atan(Math.abs(distanceY / distanceX)));
}
if (angle < 45) {
return true; // 判定為橫向滑動,自己攔下來
}
break;
}
return mViewDragHelper.shouldInterceptTouchEvent(ev);
}
@Override
public boolean onTouchEvent(MotionEvent ev) {
ViewParent viewParent = getParent();
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mDownX = ev.getRawX();
mDownY = ev.getRawY();
break;
case MotionEvent.ACTION_MOVE:
float distanceX = ev.getRawX() - mDownX;
float distanceY = ev.getRawY() - mDownY;
float angle;
if (distanceX == 0) {
angle = 90;
} else {
angle = (float) Math.toDegrees(
Math.atan(Math.abs(distanceY / distanceX)));
}
if (angle < 45 && viewParent != null) {
// 橫向滑動時,請父容器(例如 ListView)不要來搶事件
viewParent.requestDisallowInterceptTouchEvent(true);
}
break;
case MotionEvent.ACTION_CANCEL:
case MotionEvent.ACTION_UP:
if (viewParent != null) {
viewParent.requestDisallowInterceptTouchEvent(false);
}
break;
}
mViewDragHelper.processTouchEvent(ev);
return true;
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b) {
super.onLayout(changed, l, t, r, b);
int measureHeight = mBottomView.getMeasuredHeight();
int measureWidth = mBottomView.getMeasuredWidth();
// 底層菜單:靠右邊界、垂直居中,藏在 mTopView 後面
mBottomView.layout(mWidth - measureWidth, (mHeight - measureHeight) / 2,
mWidth, mHeight + measureHeight / 2);
// 若目前是展開狀態,mTopView 要往左移一個菜單寬
if (mState == OPEN) {
mTopView.layout(-measureWidth, 0,
mTopView.getMeasuredWidth() - measureWidth,
mTopView.getMeasuredHeight());
}
}
@Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
super.onSizeChanged(w, h, oldw, oldh);
mWidth = w;
mHeight = h;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
if (getChildCount() != 2) {
throw new IllegalStateException("only and should contain two child view");
}
View bottomView = getChildAt(0);
if (!(bottomView instanceof ViewGroup)) {
throw new IllegalStateException("sideslip menu should be contained by a viewgroup");
}
mBottomView = bottomView;
mTopView = getChildAt(1);
}
/** 吸附到左邊(展開菜單)。僅能在 onViewReleased 中呼叫 */
private void scrollToLeftEdge() {
mViewDragHelper.settleCapturedViewAt(-mBottomView.getMeasuredWidth(), 0);
invalidate();
mState = OPEN;
if (mSwipeListener != null) {
mSwipeListener.onOpenListener(this);
}
}
/** 吸附到右邊(收起菜單)。僅能在 onViewReleased 中呼叫 */
private void scrollToRightEdge() {
mViewDragHelper.settleCapturedViewAt(0, 0);
invalidate();
mState = CLOSE;
}
/** 外部主動收起 */
public void smoothClose() {
mViewDragHelper.smoothSlideViewTo(mTopView, 0, 0);
invalidate();
mState = CLOSE;
}
public int getState() {
return mState;
}
public void setState(int state) {
mState = state;
invalidate();
}
public interface SwipeListener {
void onOpenListener(SwipeLayout swipeLayout);
}
public void setSwipeListener(SwipeListener mSwipeListener) {
this.mSwipeListener = mSwipeListener;
}
}
效果圖:

1. 為什麼用 ViewDragHelper 而不是自己算位移?
手寫拖拽要處理多指觸控、邊界裁剪、速度計算、fling 動畫,細節非常多。ViewDragHelper 把這些封裝好了,我們只需要回答三個問題:誰可以拖(tryCaptureView)、拖的極限在哪(clampViewPositionHorizontal/Vertical)、鬆手後停在哪(onViewReleased)。
2. 為什麼 onFinishInflate 要檢查子 View 數量?
在 inflate 階段就驗證結構,能讓錯誤在畫面出現之前就被丟出來,比後續拿到 null 再崩潰容易 debug 得多。這裡也順帶檢查了底層必須是 ViewGroup。
3. 事件攔截的雙保險
onInterceptTouchEvent 用「位移角度小於 45 度」判定橫向手勢,onTouchEvent 中再呼叫 requestDisallowInterceptTouchEvent(true) 阻止外層 ListView 搶走事件。兩處搭配,才能在做在列表中的側滑時不會與列表滾動打架——這正是側滑控件最容易出問題的地方。
4. computeScroll 不能少
ViewDragHelper 的吸附是「逐幀逼近」的動畫,靠 continueSettling(true) 回報是否還在動。少了 computeScroll 的 invalidate,動畫只會跑一幀就停住。
STATE_DRAGGING 與 STATE_SETTLING 狀態,讓外部能精確掌握動畫階段。以上就是這個精簡版 SwipeLayout 的完整解析。整體來說,ViewDragHelper 負責手勢與動畫,我們只負責回答「停在哪」,這也是目前實作側滑效果最省事的路線。
Android SQLite 使用指南與七大效能優化實務
寫在前面的話 今天我們來學習如何在 Android 中使用 SQLite,以及如何對資料庫操作進行效能優化。SQLite 是行動裝置上最常用的輕量級關聯式資料庫,掌握它的
自繪 MTextView 解決中文提前換行問題,同時支援圖文混排
用 Android 原生 TextView 排版中文時,常會遇到一個惱人的現象:明明這一行還有很多空間,最後幾個字卻被整批丟到下一行。下面這張圖裡,上方是自繪的 MTex
Android Timer 定時輪詢實作:定期抓取伺服器時間的完整範例
這個範例示範如何用 Timer 做定時輪詢:按下開始鈕之後,每 2 秒向後端請求一次時間,透過 Handler 把結果回送到主執行緒更新畫面,按下停止鈕則取消排程。 一、
ViewPager + TabLayout 打造新聞焦點圖輪播
做新聞類 App 時,首頁頂端的焦點新聞輪播幾乎是標配。這裡用 ViewPager 搭配 TabLayout 實作一個帶底部指示點的輪播元件,並記錄實作過程中踩到的版面坑