'OnTouchListener for ViewPager2

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?



Solution 1:[1]

The right way to add customised onTouch logic is to call

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

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 ABU Ali14Q