解決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; }新聞熱點
疑難解答