解决ViewPager2嵌套RecyclerView滑动冲突的问题

viewPager2嵌套recyclerView滑动冲突,本来重写ViewPager2或RecyclerViewImpl的onInterceptTouchEvent方法是最好的,但是ViewPager2是个final类,无法重写,而RecyclerViewImpl是ViewPager2的私有类,也无法被继承,所以要解决滑动冲突,就只能重写RecyclerView了

重写RecyclerView的dispatchTouchEvent方法

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);
    }

}

 

你可能感兴趣的:(解决ViewPager2嵌套RecyclerView滑动冲突的问题)