Getting a Fully-Expanded RecyclerView to Scroll With Other Content On the Page
Let us say you have a view that has some content at the top (which we will call the header), followed by a RecyclerView at the bottom. And you want both to scroll together as one, so when you scroll the page up, the header scrolls up with the RecyclerView contents at the bottom. This effectively means that you do not want the RecyclerView to have its own nested scrolling (which it typically does by default). Rather, you want its contents fully expanded in the parent view so that it can scroll as a unit with the header at the top (and possibly other content on the page, like maybe a footer at the bottom).
One way to do this is to (a) turn off the nested scrolling for RecyclerView by settingandroid:nestedScrollingEnabled="false"
(note this only works in API 21 and above) and then (b) placing the header and RecyclerView inside of a verical LinearLayout (or other equivalent Layout) and make that LinearLayout a child of ScrollView, like so:
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="36sp"
android:background="@color/headerBackground"
android:text="@string/headerText" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/goals"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>
</LinearLayout>
</ScrollView>
In theory this should work. But in practice what happens is the RecyclerView’s contents get truncated. In other words, it does not show all of its items.
It seems that when embedded in a ScrollView, the RecyclerView is not measured correctly. I’ll admit I’m not sure why that is the case.
But there is a simple solution to this. Use NestedScrollView instead of ScrollView. So we can change the above from ScrollView to NestedScrollView like so:
<androidx.core.widget.NestedScrollView
android:layout_width="match_parent"
android:layout_height="match_parent">
<LinearLayout
android:layout_width="match_parent"
android:orientation="vertical"
android:layout_height="wrap_content">
<TextView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:textSize="36sp"
android:background="@color/headerBackground"
android:text="@string/headerText" />
<androidx.recyclerview.widget.RecyclerView
android:id="@+id/goals"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:nestedScrollingEnabled="false"
app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
/>
</LinearLayout>
</androidx.core.widget.NestedScrollView>
And now when we run the code again we can see all elements in the RecyclerView as we scroll to the bottom: