Search code examples
androidandroid-jetpack-composeandroid-jetpack

Jetpack Compose: How to add different amount of spacings to different contentTypes in LazyColumn?


I have a LazyColumn that displays numerous views with distinct contentType values, (viewType in the terminology of the RecyclerView).

Let's consider that this is my LazyColumn:

LazyColumn {
   items(itemsOfContentType1.size) {
       Content1Item(itemsOfContentType1[it])
   }
   items(itemsOfContentType2.size) {
       Content2Item(itemsOfContentType2[it])
   }
   items(itemsOfContentType3.size) {
       Content3Item(itemsOfContentType3[it]) // Want to add a spacer between these items!
   }
}

My objective is to have no spacing between items with contentType=1 and contentType=2, while introducing an 8dp gap between items with contentType=3.

How can I accomplish this?


Solution

  • I've implemented a workaround to wrap my items in a Column to add spacing between these items like this:

    LazyColumn {
       items(itemsOfContentType1.size) { index ->
           Content1Item(itemsOfContentType1[index])
       }
       items(itemsOfContentType2.size) { index ->
           Content2Item(itemsOfContentType2[index])
       }
       items(itemsOfContentType3.size) { index ->
           Column {
               if (index > 0) {
                   Spacer(modifier = Modifier.height(8.dp)) // Adding spacer between items
               }
               Content3Item(itemsOfContentType3[it])
           }
       }
    }
    

    This solution aligns perfectly with my desired outcome. However, I'm wondering whether there might be a simpler way to implement this logic.