How to disable ViewPager scrolling on diagonal swipes in Android?

Viewed 53

Sketch that tries to explain what I mean

I have an Activity with a ViewPager, which hosts several pages, each containing a RecyclerView. Horizontal and vertical swipes are working as expected: Horizontal changes the page, vertical scrolls the RecyclerView.

When the user makes a diagonal swipe, the page changes.

How can I prevent this? Diagonal swipes should only scroll the RecyclerView.

<?xml version="1.0" encoding="utf-8"?>
<androidx.viewpager2.widget.ViewPager2
   xmlns:android="http://schemas.android.com/apk/res/android"
   android:id="@+id/page"
   android:layout_width="match_parent"
   android:layout_height="match_parent" />

I already tried this:

binding.page.setOnTouchListener(object : View.OnTouchListener {
   override fun onTouch(v: View?, event: MotionEvent?): Boolean {
      when (event?.action) {
         MotionEvent.ACTION_DOWN -> binding.page.isUserInputEnabled = false
      }
      return v?.onTouchEvent(event) ?: true
   }
})
1 Answers

I just tested out the behavior you described. In my opinion ViewPager2 and RecyclerView work together flawlessly: On a diagonal swipe with less than 45°, the ViewPager2 gets scrolled. On diagonal swipes with more than 45°, the RecyclerView gets scrolled.

However, this seems only true when the Activity is newly created. It also seems to depend a little bit on the prior scroll gesture.

  • When you first make a vertical swipe (RecyclerView gets scrolled), after that, diagonal scrolls again will scroll the RecyclerView.
  • When you just made a horizontal swipe (ViewPager2 gets scrolled), then diagonal scrolls tend to scroll the ViewPager2.

Maybe this is the intended behavior. To provide a more intuitive user experience,
I'd probably keep it as is, as I had to test quite some time to reproduce your described behavior.
Actually, all the scrolling felt very intuitive the way it is.

And keep in mind: If you really only want to allow exactly 0° horizontal swipes to scroll the ViewPager2, you're giving your users a very hard time. It would be practically impossible to scroll the ViewPager2.

Related