My RecyclerView in ViewPager2 does not scroll.
The documentation of ViewPager2 has a section about nested scrollable elements, but it is about elements having the same orientation as the ViewPager2. I have different orientations in ViewPager2 (horizontal) and RecyclerView (vertical).
How can I make the RecyclerView scroll? What am I doing wrong? Code from layout files:
RecyclerView-fragment code:
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools">
// ...
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/pieces_list"
android:orientation="vertical"
android:layout_width="0dp"
android:layout_height="0dp"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager" />
</layout>
Code of fragment containing ViewPager2:
<androidx.coordinatorlayout.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<com.google.android.material.tabs.TabLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="@+id/tabs"
style="@style/AppTabLayout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:tabGravity="fill"
app:tabMaxWidth="0dp"
app:tabMode="fixed"
app:tabTextAppearance="@style/AppTabTextAppearance" />
<androidx.viewpager2.widget.ViewPager2
android:id="@+id/viewPager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
</androidx.coordinatorlayout.widget.CoordinatorLayout>
I connect them with FragmentStateAdapter
and TabLayoutMediator
in my fragment code, if this matters.
The bug was not in my RecyclerView
or ViewPager2
setup. I am also using the AppBarLayout
. I did not put app:layout_scrollFlags="scroll|enterAlways"
on the child layout which contained my ViewPager2
with RecyclerView
. But each child of AppBarLayout
must specify app:layout_scrollFlags
in order for it to be scrollable.
Moreover, ViewPager2
and RecyclerView
should not be a child of AppBarLayout
, but be right below the AppBarLayout
tag. I moved them out of the AppBarLayout
and now everything works as expected.