如何使ViewPager2的滑动灵敏度降低?

10

我的 ViewPager2 包含了带 RecyclerView 的片段。当我在适配器中向下或向上滚动时,它经常会“滑动”到下一个或上一个视图页面片段,即使适配器只有几个项目(不占据整个屏幕)。是否有办法降低这个新版 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" />
1个回答

9

以下代码适用于 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) {
    }

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接