public class MyViewPager extends ViewPager { private RecyclerView recyclerView; public MyViewPager(@NonNull Context context) { super(context); } public MyViewPager(@NonNull Context context, @Nullable AttributeSet attrs) { super(context, attrs); } public void setView(RecyclerView recyclerView){ this.recyclerView = recyclerView; } private int startX, startY; @Override public boolean onInterceptTouchEvent(MotionEvent ev) { if(null != recyclerView){ 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));// } //第二种方法 if(endX>startX){ //表示向左滑动 isVisTop(recyclerView); }else if(endX<startX){//向右滑动 isVisBottom(recyclerView); } break; case MotionEvent.ACTION_UP: case MotionEvent.ACTION_CANCEL: getParent().requestDisallowInterceptTouchEvent(false); break; } return super.onInterceptTouchEvent(ev); }else{ return super.onInterceptTouchEvent(ev); } } public static boolean isVisBottom(RecyclerView recyclerView){ LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); //屏幕中最后一个可见子项的position int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition(); //当前屏幕所看到的子项个数 int visibleItemCount = layoutManager.getChildCount(); //当前RecyclerView的所有子项个数 int totalItemCount = layoutManager.getItemCount(); //RecyclerView的滑动状态 int state = recyclerView.getScrollState(); if(visibleItemCount > 0 && lastVisibleItemPosition == totalItemCount - 1 ){ return true; }else { return false; } } public static boolean isVisTop(RecyclerView recyclerView){ LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager(); //屏幕中最后一个可见子项的position int lastVisibleItemPosition = layoutManager.findLastVisibleItemPosition(); //当前屏幕所看到的子项个数 int visibleItemCount = layoutManager.getChildCount(); //当前RecyclerView的所有子项个数 int totalItemCount = layoutManager.getItemCount(); //RecyclerView的滑动状态 int state = recyclerView.getScrollState(); if(visibleItemCount > 0 && lastVisibleItemPosition <visibleItemCount){ return true; }else { return false; } }}
重新viewPager拦截器onInterceptTouchEvent方法,如上面所示,滑动最左边或者最右边的时候就返回true拦截监听,交给viewPager自己处理,如果不是那就返回false,向下传递