Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

viewpager2 reduce sensitivity of horizontal scrolling

how can i reduce the sensitivity of horizontal scrolling in viewpager2?

this is currently my code for the viewpager.

viewPager = findViewById(id.view_pager);
viewPager.setAdapter(new ViewPagerAdapter(this, dataManager, USERNAME));
tabLayout.setSelectedTabIndicatorColor(ContextCompat.getColor(this, R.color.green));
new TabLayoutMediator(tabLayout, viewPager,
        new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                tab.setText(tabNames.get(position));
            }
        }).attach();
like image 804
encryptomator Avatar asked Mar 12 '20 19:03

encryptomator


1 Answers

I was searching for the same thing and found this solution in Kotlin:

val recyclerViewField = ViewPager2::class.java.getDeclaredField("mRecyclerView")
recyclerViewField.isAccessible = true
val recyclerView = recyclerViewField.get(this) as RecyclerView

val touchSlopField = RecyclerView::class.java.getDeclaredField("mTouchSlop")
touchSlopField.isAccessible = true
val touchSlop = touchSlopField.get(recyclerView) as Int
touchSlopField.set(recyclerView, touchSlop*8)       // "8" was obtained experimentally

If you need Java, it should be something like this:

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

    RecyclerView recyclerView = (RecyclerView) recyclerViewField.get(myViewPager);

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

    int touchSlop = (int) touchSlopField.get(recyclerView);
    touchSlopField.set(recyclerView, touchSlop * 8);
} catch (NoSuchFieldException | IllegalAccessException e) {
    e.printStackTrace();
}

This is not a “good” solution because it uses the reflection API, but it should help.

like image 94
Vladimir Avatar answered Oct 23 '22 02:10

Vladimir