How to prevent swiping in androidx ViewPager2 when the touch event is coming from inside a nested view (e.g. a HorizontalScrollView, etc)?
I expected this to be possible by overriding ViewPager2.onInterceptTouchEvent()
but since ViewPager2 is final
it cannot be subclassed.
The existing solutions (listed below) deal with the older ViewPager which can be subclassed.
As suggested in one of the answers I have tried:
private ViewPager2 viewPager2;
...
HorizontalScrollView nestedScrollView = pagerView.findViewById(R.id.scrollview);
nestedScrollView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
viewPager2.requestDisallowInterceptTouchEvent(true);
return false;
}
});
// nestedScrollView - the HorizontalScrollView inside a ViewPager2 item
// viewPager2 - the ViewPager2 instance
but this does not seem to have any effect.
ViewPager2 has onInterceptTouchEvent() inherited from ViewGroup but I don't see a way to override it on a final class.
Reimplementing the entire ViewPager2 does not seem like a sane solution — the original class is 1607 lines long and moreover it's using classes which are not exported by the package.
Other similar questions I've looked at: