The intended layout shall be a grid layout of individual items which are broken into sections by a horizontal divider and a caption. (One might thinkg of the gallery view of Google Photos.) The layout shall be scrollable as a whole. The following figure illustrates a mockup.
On the left one can see the whole (virtual) layout. On the right, one see can see the visible view port.
At a rough glance, the current XML structure of the layout looks like that:
androidx.core.widget.NestedScrollView
|
+-- LinearLayout
|
+-- TextView (the first caption)
+-- androidx.recyclerview.widget.RecyclerView
+-- View (the divider)
+-- TextView (the second caption)
+-- androidx.recyclerview.widget.RecyclerView
The height of the RecyclerView
is set to wrap_content
and setNestedScrollingEnabled( false )
is called as recommended by this answer.
Problem: Although the layout works as expected, it is inefficient. The ReyclerView
instantiates an independent object RecyclerView.ViewHolder
for each item in the whole gallery not only for the visible items. In the example: 60 objects instead of only 26. In other words, the ReyclerView
does not recycle anything. In addition, onBindViewHolder
is also called 60 times during creation of the view, which means I would eventually have to load all data at once. (When the mockup icons will be replaced by true images.)
Background: Of course, I understand the cause of the problem. From the perspective of a RecyclerView
everything is visible at once. The RecyclerView
does not know that is is embedded in a NestedScrollView
which clips away the invisible parts.
Question: How do I achieve the intended layout and benefit from advantages of a RecyclerView
(recycling of views, lazy/paged loading of data)? Maybe, using RecyclerView
is the wrong approach and I need to use something totally different.