How to add dividers between items in a LazyColumn Jetpack Compose?
Asked Answered
D

2

64

I have a LazyColumn that looks like this:

LazyColumn (
    verticalArrangement = Arrangement.spacedBy(12.dp)
) {
    items(bookList) { book ->
        InProgressBookItem(book = book)
    }
}

How can I add a line between each item in the list, similar to using an item decoration on the old RecyclerView?

Deltoro answered 17/4, 2021 at 15:38 Comment(0)
M
114

Currently there is no built–in way to add dividers. However, you can just add a Divider in the LazyListScope.

Something like:

LazyColumn(
    verticalArrangement = Arrangement.spacedBy(12.dp),
) {
    items(itemsList){
        Text("Item at  $it")
        Divider(color = Color.Black)
    }
}

If you do not want the last item to be followed by a Divider, you can add dividers to items according to their indices:

LazyColumn(
    verticalArrangement = Arrangement.spacedBy(12.dp),
) {
    itemsIndexed(itemsList) { index, item ->

        Text("Item at index $index is $item")

        if (index < itemsList.lastIndex)
            Divider(color = Color.Black, thickness = 1.dp)
    }
}

enter image description here

Moonfish answered 17/4, 2021 at 16:31 Comment(5)
This was my first thought, but I was hoping there would be a more elegant/built in way to do it. For now, this should work, thank you!Deltoro
Tip: instead of index < itemsList.size-1 you can write index < itemsList.lastIndexCaius
Or compose core team would have provided divider parameter that accepts Composable in LazyColumn function instead of forcing us do crappy workarounds like thisLungfish
Tip: add divider before the item with condition index>0Edd
What about LazyRow? This doesn't work with thatAlonaalone
O
12

Simple:

LazyColumn (
    verticalArrangement = Arrangement.spacedBy(12.dp)
) {
    items(bookList) { book ->
        InProgressBookItem(book = book)
        Divider(color = Color.Black, thickness = 1.dp)
    }
}
Opisthognathous answered 17/4, 2021 at 16:2 Comment(2)
Won't this add a divider after the final book too? I think the asker wanted them only in between elements.Hejira
It adds line after last item in the LazyColumnFreaky

© 2022 - 2024 — McMap. All rights reserved.