Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

SwipeLayout 源碼解析:用 ViewDragHelper 實現側滑顯示底層菜單

編輯:關於 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,動畫只會跑一幀就停住。

若要產品化,還可以補這些

  • 把菜單寬度、閾值比例、動畫時間抽成自定義屬性(declare-styleable)。
  • 增加 STATE_DRAGGING 與 STATE_SETTLING 狀態,讓外部能精確掌握動畫階段。
  • 支援「打開一個就關閉其他」:由父容器(例如 RecyclerView 的 ItemDecoration 或 Activity 層)統一管理當前展開的項。
  • 同時支援右滑(露出左側菜單),並處理與 RecyclerView 的嵌套滾動衝突。
  • 列表回收時記得重置狀態,否則捲動後會出現「該關的沒關」的視覺錯誤。

以上就是這個精簡版 SwipeLayout 的完整解析。整體來說,ViewDragHelper 負責手勢與動畫,我們只負責回答「停在哪」,這也是目前實作側滑效果最省事的路線。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved