Hello guys, I tried to make my own `GridLayout` wi...
# compose
j
Hello guys, I tried to make my own
GridLayout
with items as square. It’s working nicely but can you tell me if there is some improvements to do? Performance? Thank you 🙏 (That’s a nice feeling to work with layout and to see it working 😄)
Copy code
@Composable
fun GridLayout(
    modifier: Modifier = Modifier,
    columns: Int = 2,
    spaceBetween: Dp = 8.dp,
    content: @Composable () -> Unit
) {
    Layout(
        modifier = modifier,
        content = content
    ) { measurables, constraints ->

        val columnWidth = constraints.maxWidth / columns
        val itemConstraints = constraints.copy(maxWidth = columnWidth, maxHeight = columnWidth)
        val colHeights = IntArray(columns) { 0 } // track each column's height

        val placeable = measurables.mapIndexed { index, measurable ->
            val placeable = measurable.measure(itemConstraints)
            colHeights[index % columns] += placeable.height
            placeable
        }

        val height = colHeights.maxOrNull()?.coerceIn(constraints.minHeight, constraints.maxHeight)
            ?: constraints.minHeight

        layout(constraints.maxWidth, height) {
            var yPosition = 0
            var xPosition = 0
            placeable.forEachIndexed { index, placeable ->
                placeable.placeRelative(x = xPosition, y = yPosition)
                if ((index - 1) % columns == 0) {
                    xPosition = 0
                    yPosition += placeable.height + spaceBetween.toPx().toInt()
                } else {
                    xPosition += placeable.width + spaceBetween.toPx().toInt()
                }
            }
        }
    }
}