Luis Daivid

    Luis Daivid

    1 year ago
    What’s the best way to implement a view like grid recycler view? Any good examples?
    cb

    cb

    1 year ago
    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:
    LazyColumn {
        fakeGridItems(
            items = ...,
            columns = 3
        ) { item ->
            // grid item
            Box(...)
        }
    }
    Luis Daivid

    Luis Daivid

    1 year ago
    @cb Thank you~!!
    j

    Jrichards1408

    1 year ago
    nice one i will give this a go. do i just need to copy the following method below:
    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)
            }
        }
    }