拖动控件实现滑动之使用offsetLeftAndRight

再次说下前提,不修改父布局,之移动自己,也不影响父容器的其它子控件 ,也不需要使用winManager的方式插入的view

        binding.getRoot().setOnTouchListener(new View.OnTouchListener() {
            //            long pressTime = 0;
            float downX = 0;
            float downY = 0;
            boolean hasMove = false;
            int clickDistance = DensityUtil.dip2px(AppContext.getInstance(), 3);

            @Override
            public boolean onTouch(View v, MotionEvent event) {
                int actionMasked = event.getActionMasked();
                switch (actionMasked) {
//                switch (event.getAction()) {
                    case MotionEvent.ACTION_DOWN:
//                        pressTime = System.currentTimeMillis();
                        hasMove = false;
                        downX = event.getRawX();
                        downY = event.getRawY();

                        return true;
                    case MotionEvent.ACTION_MOVE:

                        hasMove = true;
                        View root = binding.getRoot();


                        float distanceX = event.getRawX() - downX;//表示触摸到哪里,但是 你滑动具体是多少是得转换的
                        float distanceY = event.getRawY() - downY;

                        int leftSrc = v.getLeft();
                        int rightSrc = v.getRight();
                        int topSrc = v.getTop();
                        int bottomSrc = v.getBottom();


                        int left = (int) (root.getLeft() + distanceX);
                        int right = (int) (root.getRight() + distanceX);
                        int top = (int) (root.getTop() + distanceY);
                        int bottom = (int) (root.getBottom() + distanceY);

                        if (BuildConfig.DEBUG) {
                            Prt.w(TAG, String.format("滑动距离%f y:%f src left %d,top%d right %d bottom%d modify left %d,top%d right %d bottom%d", distanceX, distanceY, leftSrc, topSrc, rightSrc, bottomSrc, left, top, right, bottom));
                        }
                        downX = event.getRawX();
                        downY = event.getRawY();


//                        root.layout(left, top, right, bottom);//这种方法在重新绘制的时候容易还原

                        v.offsetLeftAndRight((int) distanceX);
                        v.offsetTopAndBottom((int) distanceY);
                        return true;


                    case MotionEvent.ACTION_UP:
                        if (hasMove) {
                            return true;

                        } else {
                            return false;
                        }
                    default:
                        return false;
                }
            }
        });

弊端和layout一样,必须重写父控件,否则会在某个重绘的时候导致被还原。

你可能感兴趣的:(拖动控件实现滑动之使用offsetLeftAndRight)