Skip to content

Instantly share code, notes, and snippets.

@TuenTuenna
Last active July 26, 2022 04:53
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save TuenTuenna/eeac6756f49f9bd9229954a78bb8a0b2 to your computer and use it in GitHub Desktop.
Save TuenTuenna/eeac6756f49f9bd9229954a78bb8a0b2 to your computer and use it in GitHub Desktop.
compose staggeredGrid not lazy

콤포즈 staggered grid not lazy

@Composable
fun StaggeredVerticalGrid(
  modifier: Modifier = Modifier,
  columnCount: Int = 2,
  content: @Composable () -> Unit
) {
    Layout(
      content = content,
      modifier = modifier
    ) { measurables, constraints ->
        val placeableXY: MutableMap<Placeable, Pair<Int, Int>> = mutableMapOf()

        check(constraints.hasBoundedWidth) {
            "Unbounded width not supported"
        }
        val columnWidth = constraints.maxWidth / columnCount
        val itemConstraints = constraints.copy(maxWidth = columnWidth)
        val colHeights = IntArray(columnCount) { 0 } // track each column's height
        val placeables = measurables.map { measurable ->
            val column = shortestColumn(colHeights)
            val placeable = measurable.measure(itemConstraints)
            placeableXY[placeable] = Pair(columnWidth * column, colHeights[column])
            colHeights[column] += placeable.height
            placeable
        }

        val height = colHeights.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
}

참조: https://medium.com/mobile-app-development-publication/staggeredverticalgrid-of-android-jetpack-compose-fa565e5363e1

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