Disable ViewPager paging when child recyclerview scrolls to last item
Here is solution.
requestDisallowInterceptTouchEvent()
This method will not allow parent to move. It stops viewpager touch event.
horizontalRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
int action = e.getAction();
switch (action) {
case MotionEvent.ACTION_MOVE:
rv.getParent().requestDisallowInterceptTouchEvent(true);
break;
}
return false;
}
@Override
public void onTouchEvent(RecyclerView rv, MotionEvent e) {
}
@Override
public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
}
});
In order to handle the issue with vertical scroll no longer working I did this instead:
Create a touch listener for the RecyclerView item
mGestureDetector = new GestureDetector(itemView.getContext(), new GestureListener());
/**
* Prevents the view pager from switching tabs when scrolling the carousel
*/
private class TouchListener implements RecyclerView.OnItemTouchListener {
@Override
public boolean onInterceptTouchEvent(RecyclerView rv, MotionEvent e) {
mGestureDetector.onTouchEvent(e);
return false;
}
}
And implement a GestureListener that disallows touch events when horizontal scrolls are detected:
private class GestureListener extends SimpleOnGestureListener {
private final int Y_BUFFER = 10;
@Override
public boolean onDown(MotionEvent e) {
// Prevent ViewPager from intercepting touch events as soon as a DOWN is detected.
// If we don't do this the next MOVE event may trigger the ViewPager to switch
// tabs before this view can intercept the event.
mRecyclerView.requestDisallowInterceptTouchEvent(true);
return super.onDown(e);
}
@Override
public boolean onScroll(MotionEvent e1, MotionEvent e2, float distanceX, float distanceY) {
if (Math.abs(distanceX) > Math.abs(distanceY)) {
// Detected a horizontal scroll, prevent the viewpager from switching tabs
mRecyclerView.requestDisallowInterceptTouchEvent(true);
} else if (Math.abs(distanceY) > Y_BUFFER) {
// Detected a vertical scroll of large enough magnitude so allow the the event
// to propagate to ancestor views to allow vertical scrolling. Without the buffer
// a tab swipe would be triggered while holding finger still while glow effect was
// visible.
mRecyclerView.requestDisallowInterceptTouchEvent(false);
}
return super.onScroll(e1, e2, distanceX, distanceY);
}
}