使用ViewDragHelper自定义的Layout实现拖拽功能确实很方便,怎么使用就不写了,记录一下坑,关于ViewDragHelper使用addView来动态添加View的时候,当第一个View 拖动之后,再添加一个View时,第一个View 又回到了起点位置,跟踪addView发现会调用requestLayout();
invalidate(true);
两个方法,知道了问题 就好解决了
首先先创建一个Map来存储已经添加的View的位置
private Map<View, DragLayoutParams> paramsMap = new HashMap<>();
第二在onViewReleased回调中保存位置
@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);
}
第三重写onLayout方法按照存储的位置来layout子View
@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());
}
}
}
}
这样再次发生layout的时候 也不会回到原点了