Colton Idle
11/11/2022, 2:36 PMModifier.onlyShowIfTheresEnoughSpace
Stylianos Gakis
11/11/2022, 2:56 PMFilip Wiesner
11/11/2022, 2:59 PMweight()
modifier so the item is "measured last" and then use layout()
modifier on the item and figure out if you have enough space to place it.Kevin Del Castillo
11/11/2022, 3:20 PMFrancesc
11/11/2022, 8:41 PMFrancesc
11/11/2022, 8:52 PM@Composable
fun Tiles(
modifier: Modifier = Modifier,
content: @Composable () -> Unit,
) {
Layout(
modifier = modifier,
content = content,
) { measurables, constraints ->
require(measurables.size == 4) { "No bueno" }
val heights = measurables
.map { measurable -> measurable.maxIntrinsicHeight(constraints.maxWidth) }
val requiredHeight = heights.sum()
val measurablesToPlace = if (requiredHeight <= constraints.maxHeight) {
measurables
} else {
measurables.dropLast(1)
}
val looseConstraints = constraints.copy(minHeight = 0)
val placeables = measurablesToPlace.map { measurable -> measurable.measure(looseConstraints) }
layout(
width = constraints.maxWidth,
height = placeables.sumOf { it.height },
) {
var y = 0
placeables.forEach { placeable ->
placeable.placeRelative(
x = 0,
y = y,
)
y += placeable.height
}
}
}
}
@Preview(widthDp = 360)
@Composable
fun PreviewTiles() {
PlaygroundTheme {
Surface(
color = MaterialTheme.colorScheme.background
) {
Column(
modifier = Modifier
.fillMaxWidth()
.padding(all = 16.dp),
) {
Tiles(
modifier = Modifier
.fillMaxWidth()
.height(96.dp)
) {
Text(
text = "Foo",
textAlign = TextAlign.Center,
modifier = Modifier.background(Color.Red.copy(alpha = .3f))
)
Text(
text = "Bar",
textAlign = TextAlign.Center,
modifier = Modifier.background(Color.Blue.copy(alpha = .3f))
)
Text(
text = "Baz",
textAlign = TextAlign.Center,
modifier = Modifier.background(Color.Red.copy(alpha = .3f))
)
Text(
text = "FooBarBaz",
textAlign = TextAlign.Center,
modifier = Modifier.background(Color.Blue.copy(alpha = .3f))
)
}
Tiles(
modifier = Modifier
.fillMaxWidth()
.padding(top = 16.dp)
.height(40.dp)
) {
Text(
text = "Foo",
textAlign = TextAlign.Center,
modifier = Modifier.background(Color.Red.copy(alpha = .3f))
)
Text(
text = "Bar",
textAlign = TextAlign.Center,
modifier = Modifier.background(Color.Blue.copy(alpha = .3f))
)
Text(
text = "Baz",
textAlign = TextAlign.Center,
modifier = Modifier.background(Color.Red.copy(alpha = .3f))
)
Text(
text = "FooBarBaz",
textAlign = TextAlign.Center,
modifier = Modifier.background(Color.Blue.copy(alpha = .3f))
)
}
}
}
}
}
Francesc
11/11/2022, 8:52 PMColton Idle
11/11/2022, 9:13 PM