Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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" />
like image 378
Michalsx Avatar asked May 13 '20 10:05

Michalsx


1 Answers

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) {
    }
like image 55
Michalsx Avatar answered Nov 04 '22 11:11

Michalsx