On the dynamic addview of ViewDragHelper

It's really convenient to use the customized Layout of ViewDragHelper to implement the drag function. How to use it is unnecessary to write. Record the pit. When the ViewDragHelper uses addView to dynamically add a View, when the first View is dragged and then a View is added, the first View returns to the starting point. When tracking addView, it will call requestLayout();
invalidate(true);
Two ways to solve the problem
First, create a Map to store the location of the added View

private Map<View, DragLayoutParams> paramsMap = new HashMap<>();

Second, save the location in the onViewReleased callback

             @Override
            public void onViewReleased(View releasedChild, float xvel, float yvel) {
                super.onViewReleased(releasedChild, xvel, yvel);
                DragLayoutParams params = new DragLayoutParams();
                params.mLeft = releasedChild.getLeft();
                params.mTop = releasedChild.getTop();
                params.mRight = releasedChild.getRight();
                params.mBottom = releasedChild.getBottom();
                paramsMap.put(releasedChild, params);
            }

Third, override the onLayout method to layout subviews according to the storage location

@Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        final int count = getChildCount();
        for (int i = 0; i < count; i++) {
            View child = getChildAt(i);
            if (child.getVisibility() != GONE) {
                DragLayoutParams params = paramsMap.get(child);
                if (params != null) {
                    child.layout(params.mLeft, params.mTop, params.mRight, params.mBottom);
                } else {
                    child.layout(0, 0, child.getMeasuredWidth(), child.getMeasuredHeight());
                }
            }
        }
    }

In this way, the layout will not return to the origin again

Posted on Fri, 01 May 2020 15:51:49 -0700 by dewey_witt