https://blog.csdn.net/lmj623565791/article/details/46858663
public class VDHLayout extends LinearLayout
{
private ViewDragHelper mDragger;
private View mDragView;
private View mAutoBackView;
private View mEdgeTrackerView;
private Point mAutoBackOriginPos = new Point();
public VDHLayout(Context context, AttributeSet attrs)
{
super(context, attrs);
mDragger = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback()
{
@Override
public boolean tryCaptureView(View child, int pointerId)
{
//mEdgeTrackerView禁止直接移动
return child == mDragView || child == mAutoBackView;
}
/*这个方法控制 水平方向最多能移动到的位置*/
@Override
public int clampViewPositionHorizontal(View child, int left, int dx)
{
/*左边移动最远的坐标点 已移动view的左边缘为准*/
int leftPadding = getPaddingLeft();
/*右边移动最远的横向坐标 已移动view的左边缘为准*/
int maxRight = getWidth() - getPaddingRight()-child.getWidth();
int result = Math.min(Math.max(leftPadding,left),maxRight);
return result;
}
/*定义拖动View的垂直方向的移动范围*/
@Override
public int clampViewPositionVertical(View child, int top, int dy)
{
/*上移动范围 以上边界为准*/
int topPadding = getPaddingTop();
/*下移动范围 以上边界为准*/
int maxBottom = getHeight() - getPaddingBottom()-child.getHeight();
top = Math.min(Math.max(topPadding,top),maxBottom);
return top;
}
//手指释放的时候回调
@Override
public void onViewReleased(View releasedChild, float xvel, float yvel)
{
//mAutoBackView手指释放时可以自动回去
if (releasedChild == mAutoBackView)
{
mDragger.settleCapturedViewAt(mAutoBackOriginPos.x, mAutoBackOriginPos.y);
invalidate();
}
}
/*如果拖动的view 消耗事件 或者设置完不移动 可以重写这两个方法*/
//在边界拖动时回调
@Override
public void onEdgeDragStarted(int edgeFlags, int pointerId)
{
mDragger.captureChildView(mEdgeTrackerView, pointerId);
}
/*设置childView的横向移动范围*/
@Override
public int getViewHorizontalDragRange(@NonNull View child) {
return getMeasuredWidth();
}
/*设置childView 的纵向移动范围*/
@Override
public int getViewVerticalDragRange(@NonNull View child) {
return getMeasuredHeight();
}
});
mDragger.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT|ViewDragHelper.EDGE_RIGHT);
}
@Override
public boolean onInterceptTouchEvent(MotionEvent event)
{
return mDragger.shouldInterceptTouchEvent(event);
}
@Override
public boolean onTouchEvent(MotionEvent event)
{
mDragger.processTouchEvent(event);
return true;
}
@Override
public void computeScroll()
{
if(mDragger.continueSettling(true))
{
invalidate();
}
}
@Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
super.onLayout(changed, l, t, r, b);
mAutoBackOriginPos.x = mAutoBackView.getLeft();
mAutoBackOriginPos.y = mAutoBackView.getTop();
}
@Override
protected void onFinishInflate()
{
super.onFinishInflate();
mDragView = getChildAt(0);
mAutoBackView = getChildAt(1);
mEdgeTrackerView = getChildAt(2);
}
}
网友评论