android使用recyclerview+viewpager2滑动冲突的解决

项目中最近把viewpager+fragment+recyclerview来实现首页,但是最近更换为viewpager2后,发现一些手势冲突的问题
1.fragment上下滑动异常灵敏,稍有左右偏移便会翻页
2.与recyclerview有滑动冲突问题
我的解决方法如下:
1.重新设置viewpager2的滑动灵敏度

try {
            final Field recyclerViewField = ViewPager2.class.getDeclaredField("mRecyclerView");
            recyclerViewField.setAccessible(true);

            final RecyclerView recyclerView = (RecyclerView) recyclerViewField.get(vp_rec_pager);

            final Field touchSlopField = RecyclerView.class.getDeclaredField("mTouchSlop");
            touchSlopField.setAccessible(true);

            final int touchSlop = (int) touchSlopField.get(recyclerView);
            touchSlopField.set(recyclerView, touchSlop * 4);//6 is empirical value
        } catch (Exception ignore) {
        }

2.重写recyclerview进行内部拦截手势:

public class RecyclerviewAtViewPager2 extends RecyclerView {
public RecyclerviewAtViewPager2(@NonNull Context context) {
    super(context);
}

public RecyclerviewAtViewPager2(@NonNull Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);
}

public RecyclerviewAtViewPager2(@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);
            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(canScrollHorizontally(startX -endX));
            }else {
                getParent().requestDisallowInterceptTouchEvent(canScrollVertically(startY -endY));
            }
            break;
        case MotionEvent.ACTION_UP:
        case MotionEvent.ACTION_CANCEL:
            getParent().requestDisallowInterceptTouchEvent(false);
            break;
    }
    return super.dispatchTouchEvent(ev);
}

}

你可能感兴趣的:(android使用recyclerview+viewpager2滑动冲突的解决)