19

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:

ccpizza
  • 28,968
  • 18
  • 162
  • 169
  • 2
    viewPager.userInputEnabled = false has not solved your problem? you mean nested scrolling inside a fragment in your view pager triggers swiping? – Bita Mirshafiee Jun 28 '20 at 16:58
  • 4
    @BitaMirshafiee: I need to set `viewPager.userInputEnabled = false/true` dynamically depending on where the touch event originated from: when the swipe starts in the nested HorizontalScrollVIew then it should be `false`, otherwise `true`. – ccpizza Jun 28 '20 at 20:04
  • 2
    @ccpizza did you solve this issue. Now I have similar issue, BottomSheetDialogFragment with horizontal ViewPager2. Horizontal ViewPager2 catch vertical scroll and I don't have possibility to override onInterceptTouchEvent, because ViewPager2 class is final – Ihor Levkivskyi Nov 08 '20 at 22:44
  • to allow bottomsheet be draggable over viewpager2: (bottomsheet.getChildAt(0) as RecyclerView).isNestedScrollingEnabled = false – alloha Sep 19 '22 at 17:59

0 Answers0