https://kotlinlang.org logo
#compose
Title
# compose
l

Luis Daivid

11/10/2020, 1:35 PM
What’s the best way to implement a view like grid recycler view? Any good examples?
c

cb

11/10/2020, 1:44 PM
I've been playing with this myself. You can quite easily write your own
Grid
, like the one in the Jetsnack sample: https://github.com/android/compose-samples/blob/1630f6b35ac9e25fb3cd3a64208d7c9afaaaedc5/Jetsnack/app/src/main/java/com/example/jetsnack/ui/components/Grid.kt
...but it's not lazy like
RecyclerView
. I wrote this yesterday, which displays a 'fake' grid, using `LazyColumn`: https://github.com/chrisbanes/tivi/blob/8fd534c47bb216b9033e7664e49db49661083dd2/common-ui-compose/src/main/java/app/tivi/common/compose/LazyList.kt#L130
You use it like so:
Copy code
LazyColumn {
    fakeGridItems(
        items = ...,
        columns = 3
    ) { item ->
        // grid item
        Box(...)
    }
}
l

Luis Daivid

11/11/2020, 11:41 PM
@cb Thank you~!!
j

Jrichards1408

11/18/2020, 10:05 AM
nice one i will give this a go. do i just need to copy the following method below:
Copy code
fun <T> LazyListScope.fakeGridItems(
    items: List<T>,
    columns: Int,
    contentPadding: PaddingValues = PaddingValues(),
    horizontalItemPadding: Dp = 0.dp,
    verticalItemPadding: Dp = 0.dp,
    itemContent: @Composable (T) -> Unit
) {
    val rows = when {
        items.size % columns == 0 -> items.size / columns
        else -> (items.size / columns) + 1
    }

    for (row in 0 until rows) {
        if (row == 0) spacerItem(<http://contentPadding.top|contentPadding.top>)

        item {
            Row(
                Modifier.fillMaxWidth()
                    .padding(start = contentPadding.start, end = contentPadding.end)
            ) {
                for (column in 0 until columns) {
                    Box(modifier = Modifier.weight(1f)) {
                        val index = (row * columns) + column
                        if (index < items.size) {
                            itemContent(items[index])
                        }
                    }
                    if (column < columns - 1) {
                        Spacer(modifier = Modifier.preferredWidth(horizontalItemPadding))
                    }
                }
            }
        }

        if (row < rows - 1) {
            spacerItem(verticalItemPadding)
        } else {
            spacerItem(contentPadding.bottom)
        }
    }
}
5 Views