0

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.

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.

user2690527
  • 1,729
  • 1
  • 22
  • 38
  • I think you could achieve everything you want with a single `RecyclerView`. Use `getItemViewType()` to draw the captions and dividers, and `SpanSizeLookup` to make them span the full width of the viewport. – Ben P. Feb 26 '21 at 23:43

1 Answers1

0

NestedScrollView draws all child elements, Thats why you lose all the advantages of using RecyclerView. If you want to improve this, you should use a Header (The TextView) and a Footer (Divider) for your recyclerView and avoid the NestedScrollView. Checkout this example Header/Footer in RecyclerView

Gorks
  • 120
  • 9