156_限定拖拽范围


限定拖拽范围



我们覆写ViewDragHelper.Callback中的

 

三个方法

就实现了任意拖拽

 

    ViewDragHelper.Callback callback=new ViewDragHelper.Callback() {

        @Override

        public boolean tryCaptureView(View child, int pointerId) {

            return true;

        }

 

        @Override

        public int clampViewPositionHorizontal(View child, int left, int dx) {

            return left;

        }

 

        @Override

        public int clampViewPositionVertical(View child, int top, int dy) {

            return top;

        }

    };

 

 

很好记return true,return left,return top

就这么简单

 

 

 

如果我们想限定拖拽范围,怎么做

 

首先我们要判定是哪个控件

 

判定之前我们得获得子控件

但是我们不能在构造函数中去获取

因为构造函数初始化的时候,子控件都还没有被添加进去

所以我们在onFinishInflate方法中去获取

 

 

    @Override

    protected void onFinishInflate() {

        super.onFinishInflate();

        mLeftMenu = (ViewGroup) getChildAt(0);

        mMainContent = (ViewGroup) getChildAt(1);

    }

 

 

 

 

 

然后我们让左菜单不动

那么我们就判断是不是主面板就行了

如果不是,就返回false,那么就拖拽不了了

 

 

        @Override

        public boolean tryCaptureView(View child, int pointerId) {

            return child==mMainContent;

        }

 

 

 

 

 

我们获取一下宽高

 

我们不用onMeasure

我们用一个onSizeChanged

这个方法是在onMeasureonLayout之间执行的

我们给给定一个拖拽范围60%

 

 

    @Override

    protected void onSizeChanged(int w, int h, int oldw, int oldh) {

        super.onSizeChanged(w, h, oldw, oldh);

        mHeight = getMeasuredHeight();

        mWidth = getMeasuredWidth();

        mRange = (int) (mWidth * 0.6f);

    }

 

 

 

 

然后限定拖拽范围

 

 

 

        @Override

        public int clampViewPositionHorizontal(View child, int left, int dx) {

            if (child == mMainContent) {

                if (left < 0) {

                    left = 0;

                } else if (left > mRange) {

                    left = mRange;

                }

            }

            return left;

        }

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 

 


转载自:https://blog.csdn.net/qq_33781658/article/details/51511358

You may also like...