/** * Created by Kurt on 2015/12/10. */ public class MyLayout extends LinearLayout { private ViewDragHelper MyDrager; private View MyFirst; private View MySecond; private View MyThird; private Point MysecondPoint = new Point(); /*ViewDragHelper是写入自定义viewgroup实用类。它提供了一个数字 用于允许用户拖动和重新定位的有用的操作和状态跟踪 在它们的父ViewGroup视图。 */ public MyLayout(Context context, AttributeSet attrs) { super(context, attrs); /* 第一个参数:viewgroup对象 第二个参数:sensitivity 用于设置touchSlop(主要与灵敏度有关,偏移量达到这个值则触发移动事件) TouchSlop = (int) (TouchSlop * (1 / sensitivity)); 第三个参数:回调接口 MyDrager拦截事件后交给此callback进行处理 */ MyDrager = ViewDragHelper.create(this, 1.0f, new ViewDragHelper.Callback() { @Override public boolean tryCaptureView(View child, int pointerId) { return child == MyFirst || child == MySecond; } @Override public int clampViewPositionHorizontal(View child, int left, int dx) { return left; } @Override public int clampViewPositionVertical(View child, int top, int dy) { return top; } //手指释放回调 @Override public void onViewReleased(View releasedChild, float xvel, float yvel) { super.onViewReleased(releasedChild, xvel, yvel); if (releasedChild == MySecond) { MyDrager.settleCapturedViewAt(MysecondPoint.x, MysecondPoint.y); invalidate(); } } //在边界触摸回调 @Override public void onEdgeDragStarted(int edgeFlags, int pointerId) { MyDrager.captureChildView(MyThird, pointerId); } }); //使用边界检测需要这句 MyDrager.setEdgeTrackingEnabled(ViewDragHelper.EDGE_LEFT); } @Override public boolean onInterceptTouchEvent(MotionEvent event) { return MyDrager.shouldInterceptTouchEvent(event); } @Override public boolean onTouchEvent(MotionEvent event) { MyDrager.processTouchEvent(event); return true; } //绘制view过程中,在ondraw方法中被调用 @Override public void computeScroll() { //此判断方法作用为 终止其他操作 后 进行重回(请查看源码分析返回值) if (MyDrager.continueSettling(true)) { invalidate(); } } //viewgroup初始化时执行 获取第二个控件的初始位置 @Override protected void onLayout(boolean changed, int l, int t, int r, int b) { super.onLayout(changed, l, t, r, b); Log.e("NIRVANA", "onLayout----->"); MysecondPoint.x = MySecond.getLeft(); MysecondPoint.y = MySecond.getTop(); } //当View中所有的子控件均被映射成xml后触发 @Override protected void onFinishInflate() { super.onFinishInflate(); MyFirst = getChildAt(0); MySecond = getChildAt(1); MyThird = getChildAt(2); } }
以上为本文主要内容。不通过此方法也可以实现view移动等操作,只是操作会更繁琐一些。