Issue
I'm currently playing around with custom Layouts in Jetpack Compose. This is what i got so far just for testing:
@Preview(widthDp = 1000, heightDp = 1000)
@Composable
fun MyLayout() {
Layout({ Box(Modifier.size(48.dp).background(Color.Blue)) }) { measurables, constraints ->
val placeables = measurables.map { it.measure(constraints) }
layout(constraints.maxWidth, constraints.maxHeight) {
placeables.forEach { it.place(0, 0) }
}
}
}
My problem here is that the Box
fills the whole layout and not only it's size of 48.dp
. Can someone explain to me why this is? I read here about creating custom layouts but couldn't find anything usefull.
Solution
Layout
size is determined by the size passed into layout(width, height)
.
Your Layout
doesn't have any modifiers, that's why it has maxWidth
/maxHeight
constraints equal to available spacing. Using layout(constraints.maxWidth, constraints.maxHeight)
has the same effect as applying Modifier.fillMaxSize
. Actually with Modifier.fillMaxSize
your'll set both max and min constraints to the available size.
To solve this you have two options:
Apply
Modifier.size
to theLayout
itself, instead of applying to theBox
- in this case max/min constraints will be48.dp
Calculate layout size depending on placeable. The actual code depend on what layout do you expect to get. Your code looks like
Box
analog, so you need maximum of all placeable sizes:layout(placeables.maxOfOrNull { it.width } ?: 0, placeables.maxOfOrNull { it.height } ?: 0) {
Answered By - Pylyp Dukhov
Answer Checked By - Timothy Miller (JavaFixing Admin)