解决DragViewHelper和RecyclerView滑动冲突
当没有recyclerview的时候 点击拖动的view 会直接走onTouchEvent回调,也就是走DragViewHelper的PRocessTouchEvent 如果有recyclerview的时候 点击会走onInterceptTouchEvent ,也就是走DragViewHelper的shouldInterceptTouchEvent, 进入源码之后
public boolean shouldInterceptTouchEvent(MotionEvent ev) { final int action = MotionEventCompat.getActionMasked(ev); final int actionIndex = MotionEventCompat.getActionIndex(ev); if (action == MotionEvent.ACTION_DOWN) { // Reset things for a new event stream, just in case we didn't get // the whole previous stream. cancel(); } if (mVelocityTracker == null) { mVelocityTracker = VelocityTracker.obtain(); } mVelocityTracker.addMovement(ev); switch (action) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); final int pointerId = ev.getPointerId(0); saveInitialMotion(x, y, pointerId); final View toCapture = findTopChildUnder((int) x, (int) y); // Catch a settling view if possible. if (toCapture == mCapturedView && mDragState == STATE_SETTLING) { tryCaptureViewForDrag(toCapture, pointerId); }}可以看到点击的时候是捕获不到我们要拖动的控件的
那么我们只需要在onInterceptTouchEvent回调中通过判断点中的view是不是自己要拖动的view 来调用shouldInterceptTouchEvent还是processTouchEvent
代码如下
@Override public boolean onInterceptTouchEvent(MotionEvent ev) { boolean isCanDragge = false; switch (ev.getAction()) { case MotionEvent.ACTION_DOWN: { final float x = ev.getX(); final float y = ev.getY(); final View toCapture = findTopChildUnder((int) x, (int) y); isCanDragge = toCapture != null && (toCapture == mLeftDragView || toCapture == mRightDragView); break; } } if (isCanDragge) { mDragger.processTouchEvent(ev); return super.onInterceptTouchEvent(ev); } else { return mDragger.shouldInterceptTouchEvent(ev); } } public View findTopChildUnder(int x, int y) { if (x >= mLeftDragView.getLeft() && x < mLeftDragView.getRight() && y >= mLeftDragView.getTop() && y < mLeftDragView.getBottom()) { return mLeftDragView; } if (x >= mRightDragView.getLeft() && x < mRightDragView.getRight() && y >= mRightDragView.getTop() && y < mRightDragView.getBottom()) { return mRightDragView; } return null; }新闻热点
疑难解答