From 751014e5d197642fa3d82e7d700b591695f9c41e Mon Sep 17 00:00:00 2001 From: Iamlooker Date: Sat, 23 Apr 2022 10:08:46 +0530 Subject: [PATCH] Staggered Grid Layout From - https://github.com/android/compose-samples/blob/0edb1926ac56c50a188be022c15117c07811fcdf/Owl/app/src/main/java/com/example/owl/ui/onboarding/Onboarding.kt#L281 --- .../looker/droidify/ui/compose/utils/Grid.kt | 57 +++++++++++++++++++ 1 file changed, 57 insertions(+) create mode 100644 src/main/kotlin/com/looker/droidify/ui/compose/utils/Grid.kt diff --git a/src/main/kotlin/com/looker/droidify/ui/compose/utils/Grid.kt b/src/main/kotlin/com/looker/droidify/ui/compose/utils/Grid.kt new file mode 100644 index 00000000..80ff3f8d --- /dev/null +++ b/src/main/kotlin/com/looker/droidify/ui/compose/utils/Grid.kt @@ -0,0 +1,57 @@ +package com.looker.droidify.ui.compose.utils + +import androidx.compose.runtime.Composable +import androidx.compose.ui.Modifier +import androidx.compose.ui.layout.Layout +import kotlin.math.max + +@Composable +fun StaggeredGrid( + modifier: Modifier = Modifier, + rows: Int = 3, + content: @Composable () -> Unit +) { + Layout( + content = content, + modifier = modifier + ) { measurables, constraints -> + val rowWidths = IntArray(rows) { 0 } // Keep track of the width of each row + val rowHeights = IntArray(rows) { 0 } // Keep track of the height of each row + + // Don't constrain child views further, measure them with given constraints + val placeables = measurables.mapIndexed { index, measurable -> + val placeable = measurable.measure(constraints) + + // Track the width and max height of each row + val row = index % rows + rowWidths[row] += placeable.width + rowHeights[row] = max(rowHeights[row], placeable.height) + + placeable + } + + // Grid's width is the widest row + val width = rowWidths.maxOrNull()?.coerceIn(constraints.minWidth, constraints.maxWidth) + ?: constraints.minWidth + // Grid's height is the sum of each row + val height = rowHeights.sum().coerceIn(constraints.minHeight, constraints.maxHeight) + + // y co-ord of each row + val rowY = IntArray(rows) { 0 } + for (i in 1 until rows) { + rowY[i] = rowY[i - 1] + rowHeights[i - 1] + } + layout(width, height) { + // x co-ord we have placed up to, per row + val rowX = IntArray(rows) { 0 } + placeables.forEachIndexed { index, placeable -> + val row = index % rows + placeable.place( + x = rowX[row], + y = rowY[row] + ) + rowX[row] += placeable.width + } + } + } +} \ No newline at end of file