Michalsx
Michalsx

Reputation: 3621

How to make ViewPager2 less sensitive to swipe?

My ViewPager2 contains fragments with RecyclerView. When I scroll down and up inside adapter, which has a few items (not cover whole screen), it very often "swype" to next or previous fragment in view pager. Is there any way to decrease sensitivity for this new version of ViewPager2?

<androidx.viewpager2.widget.ViewPager2 xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />

<androidx.recyclerview.widget.RecyclerView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/recyclerView"
    android:layout_width="match_parent"
    android:layout_height="match_parent" />

Upvotes: 10

Views: 2955

Answers (1)

Michalsx
Michalsx

Reputation: 3621

Following code works for ViewPager2:

    try {
        final Field recyclerViewField = ViewPager2.class.getDeclaredField("mRecyclerView");
        recyclerViewField.setAccessible(true);

        final RecyclerView recyclerView = (RecyclerView) recyclerViewField.get(viewPager);

        final Field touchSlopField = RecyclerView.class.getDeclaredField("mTouchSlop");
        touchSlopField.setAccessible(true);

        final int touchSlop = (int) touchSlopField.get(recyclerView);
        touchSlopField.set(recyclerView, touchSlop * 6);//6 is empirical value
    } catch (Exception ignore) {
    }

Upvotes: 9

Related Questions