ViewDragHelper實踐---實現(xiàn)抽屜式自定義控件VDragLayout

一、背景

????????ViewDragHelper是處理手勢事件的神兵利器,在此使用它來實現(xiàn)一個可上下滑動抽屜式的自定義控件--VDragLayout。
????????實現(xiàn)功能:
????????1、可以根據(jù)手勢的速度快慢開關(guān)抽屜;
????????2、松開手指滑動速度小于設(shè)定值時,當(dāng)顯示的區(qū)域超過可滑動的區(qū)域一半,就打開抽屜,否則關(guān)閉;
????????3、開關(guān)的方向,可以向上或向下;
????????4、當(dāng)手指點(diǎn)擊時不在子View的范圍內(nèi),不獲取處理事件;

二、實現(xiàn)

???????? 第一步:初始化ViewDragHelper

????????使用靜態(tài)方法:ViewDragHelper.create(ViewGroup forParent, Callback cb)

      //初始化ViewDragHelper
      mDragHelper = ViewDragHelper.create(this, new ViewDragCallback());
???????? 第二步:ViewDragHelper獲取事件

????????在ViewGroup的onTouchEvent方法里傳入事件,注意要返回true,表示消費(fèi)了事件。

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //ViewDragHelper傳入事件
         mDragHelper.processTouchEvent(event);
         return true;
    }
???????? 第三步:創(chuàng)建ViewDragHelper.Callback的實例

????????實例即第一步中的Callback,復(fù)寫必要的方法:

private class ViewDragCallback extends ViewDragHelper.Callback {

        /**
         * 確定是否分析view的touch
         */
        @Override
        public boolean tryCaptureView(@NonNull View view, int i) {
            return view == mChildView;
        }

        /**
         * touch移動之后的垂直方向回調(diào)分析
         *
         * @param child capture的view/移動的view
         * @param top   child的頂部距離
         * @param dy    垂直方向增量y
         * @return 返回要移動的距離
         */
        @Override
        public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
            if (child == mChildView) {
                //向上滑動
                if (mDirection == UP) {
                    if (top > 0) {
                        return 0;
                    } else if (-top > mCanOffsetHeight) {
                        return -mCanOffsetHeight;
                    }
                } else if (mDirection == DOWN) {
                    if (top < 0) {
                        return 0;
                    } else if (top > mCanOffsetHeight) {
                        return mCanOffsetHeight;
                    }
                }
            }
            return top;
        }

        /**
         * 當(dāng)控件位置移動時的回調(diào)
         * @param changedView  位置改變的View
         * @param left         左側(cè)距離
         * @param top          頂部距離
         * @param dx           水平方向增量
         * @param dy           垂直方向增量
         */
        @Override
        public void onViewPositionChanged(@NonNull View changedView, int left, int top, int dx, int dy) {
            ViewCompat.postInvalidateOnAnimation(VDragLayout.this);
        }

        /**
         * 手勢釋放時回調(diào):松開,判斷超過一半,則打開,沒超過一半則回歸原位
         * @param releasedChild
         * @param xvel            釋放時水平方向速度
         * @param yvel            釋放時垂直方向速度
         */
        @Override
        public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) {
            if (Math.abs(yvel) > mVelocityLimit) {
                boolean isShow = (yvel > 0 && mDirection == UP) || (yvel < 0 && mDirection == DOWN);
                if (isShow) {
                    toggle(true);
                } else {
                    toggle(false);
                }
                return;
            }
            int top = mChildView.getTop();
            boolean isShow = (mDirection == UP && -top < mCanOffsetHeight / 2)
                    || (mDirection == DOWN && top < mCanOffsetHeight / 2);
            if (isShow) {
                toggle(true);
            } else {
                toggle(false);
            }
        }
    }

    /**
     * 顯示隱藏切換方法
     *
     * @param isShow 是否顯示
     */
    public void toggle(boolean isShow) {
        if (mOnDragListener != null) {
            mOnDragListener.onDragChanged(VDragLayout.this, isShow);
        }
        mDragHelper.smoothSlideViewTo(mChildView, 0, isShow ? 0
                : (mDirection == UP ? -mCanOffsetHeight : mCanOffsetHeight));
        ViewCompat.postInvalidateOnAnimation(VDragLayout.this);
    }

???????? 第四步:手勢釋放時,平滑過渡到目標(biāo)位置

????????調(diào)用方法smoothSlideViewTo(@NonNull View child, int finalLeft, int finalTop)來平滑過渡到目標(biāo)位置,注意要在ViewGroup的computeScroll方法中,調(diào)用ViewDragHelper的方法continueSettling(true),并當(dāng)返回true時重新渲染,否則不會移動。

@Override
    public void computeScroll() {
        if (mDragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(VDragLayout.this);
        }
    }
????????第五步:onTouchEvent方法

????????繼續(xù)處理,當(dāng)手指點(diǎn)擊時觸摸點(diǎn)不在子View的范圍內(nèi),不獲取處理事件返回false,否則傳入ViewDragHelper,返回true。

@Override
    public boolean onTouchEvent(MotionEvent event) {
        //點(diǎn)擊時是否在子View的范圍內(nèi),在范圍內(nèi)就傳入事件,返回true攔截事件,否則返回false,不處理事件
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            int[] location = new int[2];
            mChildView.getLocationOnScreen(location);
            int left = location[0];
            int top = location[1];
            int right = left + mChildView.getMeasuredWidth();
            int bottom = top + mChildView.getMeasuredHeight();
            int x = (int) event.getRawX();
            int y = (int) event.getRawY();
            isDownInbound = x >= left && x <= right && y >= top && y <= bottom;
            if (!isDownInbound) {
                return false;
            }
        }
        if (isDownInbound) {
            //ViewDragHelper傳入事件
            mDragHelper.processTouchEvent(event);
            return true;
        }
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            isDownInbound = false;
        }
        return false;
    }

三、全部代碼

public class VDragLayout extends ViewGroup {
    private final int UP = 0;
    private final int DOWN = 1;
    private ViewDragHelper mDragHelper;
    private View mChildView;
    private float mOffsetPercent;
    private int mCanOffsetHeight;
    private int mDirection = UP;
    private int mVelocityLimit = 1000;
    private boolean isDownInbound = false;
    private OnDragListener mOnDragListener;

    public VDragLayout(Context context) {
        this(context, null);
    }

    public VDragLayout(Context context, @Nullable AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public VDragLayout(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        //初始化ViewDragHelper
        mDragHelper = ViewDragHelper.create(this, new ViewDragCallback());
        //獲取滑動的百分比
        TypedArray typedArray = context.obtainStyledAttributes(attrs, R.styleable.VDragLayout);
        mOffsetPercent = typedArray.getFloat(R.styleable.VDragLayout_OffsetPercent, 0.9f);
        mDirection = typedArray.getInt(R.styleable.VDragLayout_OffsetDirection, UP);
        int dragLevel = typedArray.getInt(R.styleable.VDragLayout_DragLevel, 2);
        if (mOffsetPercent < 0) {
            mOffsetPercent = 0;
        }
        mOffsetPercent = mOffsetPercent > 1 ? 1.0f : mOffsetPercent;
        mVelocityLimit = dragLevel == 2 ? 1000 : (dragLevel == 0 ? 2000 : 1500);
    }

    @Override
    protected void onFinishInflate() {
        //只能有一個孩子
        int childCount = getChildCount();
        if (childCount > 1) {
            throw new UnsupportedOperationException("VDragLayout cannot contain more than two child view!");
        }
        mChildView = getChildAt(0);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        mChildView.layout(0, 0, mChildView.getMeasuredWidth(), mChildView.getMeasuredHeight());
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        mChildView.measure(widthMeasureSpec, heightMeasureSpec);
        setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec), mChildView.getMeasuredHeight());
        //可以滑動的距離
        mCanOffsetHeight = (int) (mChildView.getMeasuredHeight() * mOffsetPercent);
    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        int action = event.getAction();
        if (action == MotionEvent.ACTION_DOWN) {
            int[] location = new int[2];
            mChildView.getLocationOnScreen(location);
            int left = location[0];
            int top = location[1];
            int right = left + mChildView.getMeasuredWidth();
            int bottom = top + mChildView.getMeasuredHeight();
            int x = (int) event.getRawX();
            int y = (int) event.getRawY();
            isDownInbound = x >= left && x <= right && y >= top && y <= bottom;
            if (!isDownInbound) {
                return false;
            }
        }
        if (isDownInbound) {
            mDragHelper.processTouchEvent(event);
            return true;
        }
        if (action == MotionEvent.ACTION_UP || action == MotionEvent.ACTION_CANCEL) {
            isDownInbound = false;
        }
        return false;
    }

    private class ViewDragCallback extends ViewDragHelper.Callback {

        /**
         * 確定是否分析view的touch
         */
        @Override
        public boolean tryCaptureView(@NonNull View view, int i) {
            return view == mChildView;
        }

        /**
         * touch移動之后的垂直方向回調(diào)分析
         *
         * @param child capture的view/移動的view
         * @param top   child的頂部距離
         * @param dy    垂直方向增量y
         * @return 返回要移動的距離
         */
        @Override
        public int clampViewPositionVertical(@NonNull View child, int top, int dy) {
            if (child == mChildView) {
                //向上滑動
                if (mDirection == UP) {
                    if (top > 0) {
                        return 0;
                    } else if (-top > mCanOffsetHeight) {
                        return -mCanOffsetHeight;
                    }
                } else if (mDirection == DOWN) {
                    if (top < 0) {
                        return 0;
                    } else if (top > mCanOffsetHeight) {
                        return mCanOffsetHeight;
                    }
                }
            }
            return top;
        }

        /**
         * 當(dāng)控件位置移動時的回調(diào)
         * @param changedView  位置改變的View
         * @param left         左側(cè)距離
         * @param top          頂部距離
         * @param dx           水平方向增量
         * @param dy           垂直方向增量
         */
        @Override
        public void onViewPositionChanged(@NonNull View changedView, int left, int top, int dx, int dy) {
            ViewCompat.postInvalidateOnAnimation(VDragLayout.this);
        }

        /**
         * 手勢釋放時回調(diào):松開,判斷超過一半,則打開,沒超過一半則回歸原位
         * @param releasedChild
         * @param xvel            釋放時水平方向速度
         * @param yvel            釋放時垂直方向速度
         */
        @Override
        public void onViewReleased(@NonNull View releasedChild, float xvel, float yvel) {
            if (Math.abs(yvel) > mVelocityLimit) {
                boolean isShow = (yvel > 0 && mDirection == UP) || (yvel < 0 && mDirection == DOWN);
                if (isShow) {
                    toggle(true);
                } else {
                    toggle(false);
                }
                return;
            }
            int top = mChildView.getTop();
            boolean isShow = (mDirection == UP && -top < mCanOffsetHeight / 2)
                    || (mDirection == DOWN && top < mCanOffsetHeight / 2);
            if (isShow) {
                toggle(true);
            } else {
                toggle(false);
            }
        }
    }

    @Override
    public void computeScroll() {
        if (mDragHelper.continueSettling(true)) {
            ViewCompat.postInvalidateOnAnimation(VDragLayout.this);
        }
    }

    /**
     * 顯示隱藏切換方法
     *
     * @param isShow 是否顯示
     */
    public void toggle(boolean isShow) {
        if (mOnDragListener != null) {
            mOnDragListener.onDragChanged(VDragLayout.this, isShow);
        }
        mDragHelper.smoothSlideViewTo(mChildView, 0, isShow ? 0
                : (mDirection == UP ? -mCanOffsetHeight : mCanOffsetHeight));
        ViewCompat.postInvalidateOnAnimation(VDragLayout.this);
    }

    /**
     * 設(shè)置顯示隱藏狀態(tài)更改監(jiān)聽
     *
     * @param listener
     */
    public void setOnDragListener(OnDragListener listener) {
        this.mOnDragListener = listener;
    }

    public interface OnDragListener {

        /**
         * 拖動回調(diào)
         *
         * @param view     容器view
         * @param isShowed 是否顯示
         */
        void onDragChanged(VDragLayout view, boolean isShowed);
    }
}

//attrs.xml
<declare-styleable name="VDragLayout">
        <!--滑動偏移百分比,0.0-1.0-->
        <attr name="OffsetPercent" format="float"/>
        <!--滑動方向-->
        <attr name="OffsetDirection" format="enum">
            <enum name="up" value="0"/>
            <enum name="down" value="1"/>
        </attr>
        <!--滑動手勢釋放時,顯示/隱藏的困難程度,high-->
        <attr name="DragLevel" format="enum">
            <enum name="high" value="0"/>
            <enum name="middle" value="1"/>
            <enum name="low" value="2"/>
        </attr>
    </declare-styleable>
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容