一 、原因
ViewPager2的内部实现是RecyclerView,当手势横向移动的距离大于touchSlop的时候,就会认定你有横向滑动的手势,进而驱动ViewPager2进行左右滑动
二、解决办法
重写内部嵌套的RecyclerView:
public class RecyclerViewInVP2 extends RecyclerView {
public RecyclerViewInVP2(@NonNull Context context) {
super(context);
}
public RecyclerViewInVP2(@NonNull Context context, @Nullable AttributeSet attrs) {
super(context, attrs);
}
public RecyclerViewInVP2(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
}
private int startX, startY;
@Override
public boolean dispatchTouchEvent(MotionEvent ev) {
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
startX = (int) ev.getX();
startY = (int) ev.getY();
getParent().requestDisallowInterceptTouchEvent(true);//告诉viewgroup不要去拦截我
break;
case MotionEvent.ACTION_MOVE:
int endX = (int) ev.getX();
int endY = (int) ev.getY();
int disX = Math.abs(endX - startX);
int disY = Math.abs(endY - startY);
if (disX > disY) {
getParent().requestDisallowInterceptTouchEvent(false);
} else {
getParent().requestDisallowInterceptTouchEvent(true);//下拉的时候是false
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
getParent().requestDisallowInterceptTouchEvent(true);
break;
}
return super.dispatchTouchEvent(ev);
}
}
从源码层面分析:
viewpager2+recyclerview/nestscrollview滑动冲突问题 - 掘金既然知道了是在action_move过程中是因为dx或dy大于了mTouchSlop,导致viewpager2中拦截了touch事件,所以我们有没有办法让上下滑动列表recyclerview的时候,不去拦截touch事件呢,答案就是通过上面的requestDisallowInt…https://juejin.cn/post/6886037403413250062
|