Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Scrolling behaviour conflicts with a child RecyclerView and a parent Viewpager2

I have a vertical scrolling ViewPager2 and the last children contains a RecyclerView scrolling on the same direction.

This is causing a conflicting behaviour, the ViewPager2 always steal the scroll event when I am at the page containing this RecyclerView. The only way to make the scroll inside the RecyclerView is if I scroll really slow, if I make it fast, like a swipe event the ViewPager2 gets scrolled and changes the page.

Currently I'm doing a fix that involves disabled the user interaction changing the flag isUserInputEnabled to false when the page of the ViewPager2 changes to this page that contains the RecyclerView, but a generic solution from the framework would be welcome :)

like image 240
Victor Oliveira Avatar asked Oct 16 '19 14:10

Victor Oliveira


2 Answers

I had a similar issue to yours and I found the answer via the official documentation.

I would suggest NOT to place your RecyclerView within a NestedScrollView simply for the reason Martin Marconcini answered previously. This causes the RecyclerView to create ViewHolders for every single data item, with no regards to recycling them. That is obviously very inefficient.

Instead, Google provided a solution in their ViewPager2 samples where they created a generic wrapper class called NestedScrollableHost that you simply add to your project. Then you can wrap that RecyclerView with it, similar to below, to handle the intercepted touch/swipe events:

<NestedScrollableHost
            android:layout_width="match_parent"
            android:layout_height="match_parent">

        <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/my_recycler_view"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:orientation="vertical" />

    </NestedScrollableHost>

As noted by the documentation, this only works for immediate children of the ViewPager2, which in your case should work just fine.

Hope that helps!

like image 188
Calvin Rai Avatar answered Nov 15 '22 08:11

Calvin Rai


edit child of ViewPager as RecyclerView

(binding.viewPager.getChildAt(0)as RecyclerView).isNestedScrollingEnabled = false

it's worked for me

like image 38
Max.T huang Avatar answered Nov 15 '22 09:11

Max.T huang