One Off the Slack: Matching the Parent's Size

Vsevolod Ganin asked:

I wonder why the matchParentSize modifier is available only in BoxScope? It could be useful in any layout scope I think, as well as matchParentWidth and matchParentHeight

The example use case was something like:

Column {
    Text(text = "4")
    Divider(modifier = Modifier.fillMaxWidth().preferredHeight(1.dp), color = Color.Black)
    Text(text = "2")
}

The objective is to have the Canvas() just take up the space used by the two Text() composables. Instead, fillMaxWidth() causes the Column() to want to take up the entire available width. And, since this is not in a Box(), matchParentWidth() is not an available modifier.

As Google’s Adam Powell pointed out, Box() has dedicated logic to support those modifiers:

it’s not available in every layout because it requires some special handling by the parent, and we don’t require that every custom layout perform that special handling.

matchParentSize in Box is an instruction to measure that element last, with whatever specific size the Box has already determined for itself, potentially from measuring its other child elements first.

Adam then pointed out an alternative: request a preferred width for the Column() using intrinsic size measurements. Timo Drick was able to use that to create a revised version of the sample:

Column(Modifier.preferredWidth(IntrinsicSize.Min)) {
    Text(text = "4")
    Divider(modifier = Modifier.fillMaxWidth().preferredHeight(1.dp), color = Color.Black)
    Text(text = "2")
}

Here, Timo used preferredWidth(IntrinsicSize.Min) to ask the Column() to not expand its width beyond the core requirements of the child composables. So, the Column() winds up with the width defined by the two Text() children — the fillMaxWidth() on the Divider() does not expand the Column() further.


Read the original thread in the kotlinlang Slack workspace. Not a member? Join that Slack workspace here!