美文网首页程序员
ViewDragHelper实践---实现抽屉式自定义控件VDr

ViewDragHelper实践---实现抽屉式自定义控件VDr

作者: 凌云飞鱼 | 来源:发表于2019-02-24 20:49 被阅读5次

    一、背景

            ViewDragHelper是处理手势事件的神兵利器,在此使用它来实现一个可上下滑动抽屉式的自定义控件--VDragLayout。
            实现功能:
            1、可以根据手势的速度快慢开关抽屉;
            2、松开手指滑动速度小于设定值时,当显示的区域超过可滑动的区域一半,就打开抽屉,否则关闭;
            3、开关的方向,可以向上或向下;
            4、当手指点击时不在子View的范围内,不获取处理事件;

    二、实现

             第一步:初始化ViewDragHelper

            使用静态方法:ViewDragHelper.create(ViewGroup forParent, Callback cb)

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

            在ViewGroup的onTouchEvent方法里传入事件,注意要返回true,表示消费了事件。

        @Override
        public boolean onTouchEvent(MotionEvent event) {
            //ViewDragHelper传入事件
             mDragHelper.processTouchEvent(event);
             return true;
        }
    
             第三步:创建ViewDragHelper.Callback的实例

            实例即第一步中的Callback,复写必要的方法:

    private class ViewDragCallback extends ViewDragHelper.Callback {
    
            /**
             * 确定是否分析view的touch
             */
            @Override
            public boolean tryCaptureView(@NonNull View view, int i) {
                return view == mChildView;
            }
    
            /**
             * touch移动之后的垂直方向回调分析
             *
             * @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;
            }
    
            /**
             * 当控件位置移动时的回调
             * @param changedView  位置改变的View
             * @param left         左侧距离
             * @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);
            }
    
            /**
             * 手势释放时回调:松开,判断超过一半,则打开,没超过一半则回归原位
             * @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);
        }
    
    
             第四步:手势释放时,平滑过渡到目标位置

            调用方法smoothSlideViewTo(@NonNull View child, int finalLeft, int finalTop)来平滑过渡到目标位置,注意要在ViewGroup的computeScroll方法中,调用ViewDragHelper的方法continueSettling(true),并当返回true时重新渲染,否则不会移动。

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

            继续处理,当手指点击时触摸点不在子View的范围内,不获取处理事件返回false,否则传入ViewDragHelper,返回true。

    @Override
        public boolean onTouchEvent(MotionEvent event) {
            //点击时是否在子View的范围内,在范围内就传入事件,返回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移动之后的垂直方向回调分析
             *
             * @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;
            }
    
            /**
             * 当控件位置移动时的回调
             * @param changedView  位置改变的View
             * @param left         左侧距离
             * @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);
            }
    
            /**
             * 手势释放时回调:松开,判断超过一半,则打开,没超过一半则回归原位
             * @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);
        }
    
        /**
         * 设置显示隐藏状态更改监听
         *
         * @param listener
         */
        public void setOnDragListener(OnDragListener listener) {
            this.mOnDragListener = listener;
        }
    
        public interface OnDragListener {
    
            /**
             * 拖动回调
             *
             * @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>
    

    相关文章

      网友评论

        本文标题:ViewDragHelper实践---实现抽屉式自定义控件VDr

        本文链接:https://www.haomeiwen.com/subject/ynrbyqtx.html