0

I want to populate a list (RecycleView or similar) with any number of elements in runtime.

Example:

//Data Models
Animal(spices: String, breed: Breed)  
Breed(name: String, color: String)  

The list should look something like:

Cats
-----------
Ragdoll
White

Bengal
Beige/Black

Dogs
-----------
Golden Retriever
Beige

German Shepard
Brown

St. Bernard
White/Brown

The list can be infinite long and each Animal can have an infinite amount of Breeds.
I have been using nested recyclers but I am afraid this will cause bad performance.

What is the "correct" way of populating this kind of list?

Joel Broström
  • 3,530
  • 1
  • 34
  • 61
  • This is very common in e-commerce applications where items are listed under categories like cloth might have sections for hats, shirts, pants etc. when you scroll down. – Joel Broström May 13 '20 at 07:54

1 Answers1

1

You'll need a RecyclerView Adapter with multiple wiew types. Check out this codelab, it should help you out.

Edit: the easiest way to host all this data in the adapter is to flatten it. Kind of like:

val data = mutableListOf<Object>()
animals.forEach { animal ->
    data.add(animal)
    animal.breeds.forEach { -> breed
        data.add(breed)
    }
}

// ... use the data as a source for your adapter

The item view type

override fun getItemViewType(position: Int) =
    when (getItem(position)) {
        is Animal -> ITEM_VIEW_TYPE_HEADER
        is Breed -> ITEM_VIEW_TYPE_ITEM
    }

etc etc

Alex Timonin
  • 1,872
  • 18
  • 31
  • The link is great, but they don't adress the main point I have trouble with. How would I know where to insert the correct headers? Since the sub-categories (i.e breeds) can be of any length, and the list is not hard coded, it would not be possible to just insert headers at position x,y,z. In the tutorial they just insert a header at position 0. – Joel Broström May 13 '20 at 10:28
  • I see. I might need some additional data from the inner class, but If data was an interface or Animal and Breed inherited from the same class then maybe that could work. I will try it out! Thanks again. – Joel Broström May 13 '20 at 15:36