Skip to content

Instantly share code, notes, and snippets.

@darvld
Last active August 8, 2022 05:14
Show Gist options
  • Save darvld/2ef564c3f51ba04cf3d894bd07fae2f1 to your computer and use it in GitHub Desktop.
Save darvld/2ef564c3f51ba04cf3d894bd07fae2f1 to your computer and use it in GitHub Desktop.
/*
* Copyright 2020 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* https://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
import androidx.compose.runtime.Composable
import androidx.compose.ui.Modifier
import androidx.compose.ui.layout.Layout
import androidx.compose.ui.layout.Placeable
import androidx.compose.ui.unit.Dp
import androidx.compose.ui.unit.dp
import kotlin.math.ceil
@Composable
fun StaggeredVerticalGrid(
maxColumnWidth: Dp,
modifier: Modifier = Modifier,
cellPadding: Dp = 8.dp,
content: @Composable () -> Unit
) {
Layout(
content = content,
modifier = modifier
) { measurables, constraints ->
val cellPaddingPx = cellPadding.roundToPx()
val placeableXY: MutableMap<Placeable, Pair<Int, Int>> = mutableMapOf()
check(constraints.hasBoundedWidth) {
"Unbounded width not supported"
}
val columns = ceil(constraints.maxWidth / maxColumnWidth.toPx()).toInt()
val columnWidth = (constraints.maxWidth / columns) - (cellPaddingPx / 2)
val columnHeights = IntArray(columns) { 0 } // track each column's height
val itemConstraints = constraints.copy(maxWidth = columnWidth)
val placeables = measurables.map { measurable ->
val column = shortestColumn(columnHeights)
val placeable = measurable.measure(itemConstraints)
placeableXY[placeable] = Pair((columnWidth + cellPaddingPx) * column, columnHeights[column])
columnHeights[column] += placeable.height + cellPaddingPx
placeable
}
val height = columnHeights.maxOrNull()
?.coerceIn(constraints.minHeight, constraints.maxHeight)
?: constraints.minHeight
layout(
width = constraints.maxWidth,
height = height
) {
placeables.forEach { placeable ->
placeable.place(
x = placeableXY.getValue(placeable).first,
y = placeableXY.getValue(placeable).second
)
}
}
}
}
private fun shortestColumn(colHeights: IntArray): Int {
var minHeight = Int.MAX_VALUE
var column = 0
colHeights.forEachIndexed { index, height ->
if (height < minHeight) {
minHeight = height
column = index
}
}
return column
}
@darvld
Copy link
Author

darvld commented Apr 9, 2022

You can check out the article on how to create your own staggered grid layouts here

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment