Last active
April 21, 2021 21:13
-
-
Save fvilarino/95a5e728a2e53168de67b497147c30ba to your computer and use it in GitHub Desktop.
Equal size tiles
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
@Composable | |
fun EqualSizeTiles( | |
modifier: Modifier = Modifier, | |
content: @Composable () -> Unit, | |
) { | |
Layout( | |
content = content, | |
modifier = modifier, | |
) { measurables, constraints -> | |
layoutTiles( | |
measurables, | |
constraints | |
) | |
} | |
} | |
private fun MeasureScope.layoutTiles( | |
measurables: List<Measurable>, | |
constraints: Constraints, | |
): MeasureResult { | |
val tileHeight = constraints.maxHeight | |
val tileWidths = measurables.map { measurable -> | |
measurable.maxIntrinsicWidth(tileHeight) | |
} | |
val tileWidth = tileWidths.maxOrNull() ?: 0 | |
val tileConstraints = Constraints( | |
minWidth = tileWidth, | |
minHeight = 0, | |
maxWidth = tileWidth, | |
maxHeight = constraints.maxHeight, | |
) | |
val placeables = measurables.map { measurable -> | |
measurable.measure(tileConstraints) | |
} | |
val width = (placeables.size * tileWidth).coerceAtMost(constraints.maxWidth) | |
return layout(width = width, height = tileHeight) { | |
placeables.forEachIndexed { index, placeable -> | |
placeable.place(tileWidth * index, 0) | |
} | |
} | |
} | |
@Preview(showBackground = true) | |
@Composable | |
private fun EqualSizeTilesPreview() { | |
WeatherSampleTheme { | |
Surface(modifier = Modifier | |
.width(512.dp) | |
.background(color = Color.Yellow)) { | |
EqualSizeTiles( | |
modifier = Modifier | |
.height(64.dp) | |
.background(color = Color.Green) | |
.padding(all = 8.dp) | |
) { | |
Text( | |
text = "Left", | |
textAlign = TextAlign.Center, | |
modifier = Modifier | |
.background(color = Color.Red) | |
.padding(all = 8.dp) | |
.fillMaxHeight(), | |
) | |
Text( | |
text = "Center", | |
textAlign = TextAlign.Center, | |
modifier = Modifier | |
.background(color = Color.Yellow) | |
.padding(all = 8.dp) | |
.fillMaxHeight(), | |
) | |
Text( | |
text = "Right element", | |
textAlign = TextAlign.Center, | |
modifier = Modifier | |
.background(color = Color.Blue) | |
.padding(all = 8.dp) | |
.fillMaxHeight(), | |
) | |
} | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment