androidandroid-jetpack-composeandroid-jetpack-compose-lazy-column

How can I group items together, such as a card, inside Jetpack Compose LazyColumn


Grouped result that I want

I am trying to group items like I have in my picture above where you have a header, then a grouping, such as a card, and inside the card, a list of items. I cannot figure out a way to achieve this using LazyColumn for the items inside the card. Currently, I have a list with 100+ items in a group and they are not being loaded lazily.

LazyColumn(
    contentPadding = PaddingValues(vertical = 8.dp),
    verticalArrangement = Arrangement.spacedBy(8.dp),
) {
    items(rows, key = { it.getUniqueId() }) {
        HeaderWithRows(it.title, it.innerRows) {
            Text(it.text)
        }
    }
}

@Composable
fun HeaderWithRows(
    title: String?,
    rows: List<AbstractRow>,
    itemRow: @Composable (AbstractRow) -> Unit,
) {
    Column(modifier = Modifier.padding(horizontal = 16.dp)) {
        Header(
            title = title,
            modifier = Modifier
                .padding(vertical = 8.dp)
        )
        Card {
            Column(modifier = Modifier.padding(vertical = 8.dp)) {
                rows.forEach {
                    itemRow(it)
                }
            }
        }
    }
}

I can't embed a LazyColumn inside another LazyColumn and I've tried to use the LazyListScope from the parent inside the loop and that doesn't work either.


Solution

  • If your groups are big and you want lazily load individual group items, each group item has to be inside its own item {}, there's no other way. This means you can't put them inside one Card composable - you will have to create special background for top, middle and bottom row, so that it looks like a Card when you put them together.