Skip to content

Instantly share code, notes, and snippets.

@bagus2x
Created February 5, 2022 11:05
Show Gist options
  • Save bagus2x/4af4d4444d4b74024c9b72058c1f8a64 to your computer and use it in GitHub Desktop.
Save bagus2x/4af4d4444d4b74024c9b72058c1f8a64 to your computer and use it in GitHub Desktop.
exploring jetpack compose custom Layout
sealed class StackOrientation {
object Horizontal : StackOrientation()
object Vertical : StackOrientation()
}
@Composable
fun Stack(
modifier: Modifier = Modifier,
orientation: StackOrientation = StackOrientation.Vertical,
gap: Dp = 0.dp,
content: @Composable () -> Unit
) {
Layout(
content = content,
modifier = modifier,
) { measurables, constraints ->
var width = 0
var height = 0
val isHorizontal = orientation == StackOrientation.Horizontal
val parcelables = measurables.map { measurable ->
val placeable = measurable.measure(constraints)
width += placeable.width + gap.roundToPx()
height += placeable.height + gap.roundToPx()
placeable
}
layout(
width = if (isHorizontal) width else constraints.minWidth,
height = if (!isHorizontal) height else constraints.minHeight
) {
var cursor = 0
parcelables.forEach { placeable ->
cursor += if (isHorizontal) {
placeable.place(cursor, 0)
placeable.width + gap.roundToPx()
} else {
placeable.place(0, cursor)
placeable.height + gap.roundToPx()
}
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment