4

I recently changed the ViewPager in my application to a ViewPager2. I had set an onTouchListener to the viewPager object to detect gestures (onFling and onLongPress), as such:

mViewPager.setOnTouchListener(new View.OnTouchListener() {
    @Override
    public boolean onTouch(View view, MotionEvent motionEvent) {
        mDetector.onTouchEvent(motionEvent); // use the custom gesture detector to detect onFling and onLongPress touch events.
        return true; 
    }
});

The onTouchListener for the viewPager was working fine before the refactor to the ViewPager2. I tried this answer, but it didn't work.

Anyone has an idea as to why this might be the case and how I could fix it?

Jorn Rigter
  • 745
  • 1
  • 6
  • 25

2 Answers2

15

Because ViewPager2 is a ViewGroup, the final target is the recyclerview in it. The setOnTouchListener is not called because the recyclerview intercepts the event and calls the onTouchEvent first.

The right way to add customised onTouch logic is to call

mViewPager.getChildAt(0).setOnTouchListener{...}
Jorn Rigter
  • 745
  • 1
  • 6
  • 25
geek919
  • 317
  • 3
  • 11
  • 1
    Where this code has to be put? I tried in several places (when I create the viewpager, on page select, inside the page onCreateView and onViewCreated), different child positions, but never worked. – LM_IT Jan 27 '22 at 09:21
  • wow, that's... a weird way to have to implement this. Hope they'll add an API to the pager itself at some point – avalancha May 06 '22 at 06:07
-1

The right way to add customised onTouch logic is to call

viewPager2.getChildAt(viewPager2.getCurrentItem()).setOnTouchListener(...)