Compose by example: Intrinsics
November 5, 2022
Intrinsics lets you query children before they're actually measured.
Let’s look at a basic layout example where it can be useful.
To break it down, here we have a row with 3 columns:
Row { Column { Text(...) } Column { Spacer(...) } Column { Text(...) } }
The tricky part is to make the middle column (column that contains the Spacer
) extend to the max height of this row based on the tallest column in that row. In this case, the 3rd column with long text is the tallest of the 3 so the height of the Spacer
should match the height of the text in the 3rd column.
Here is the Compose layout to achieve the above:
Row( modifier = Modifier .padding(16.dp) .border( width = 2.dp, color = Color.LightGray, shape = RoundedCornerShape(6.dp) ) .fillMaxWidth() .height(intrinsicSize = IntrinsicSize.Max) ) { Column(modifier = Modifier.padding(16.dp)) { Text( text = "Lorem ipsum", style = MaterialTheme.typography.body1, fontWeight = FontWeight.Bold, color = Color.DarkGray ) } Column( modifier = Modifier .padding(vertical = 16.dp) .background(Color.Green) ) { Spacer( modifier = Modifier .width(5.dp) .fillMaxHeight() ) } Column(modifier = Modifier.padding(16.dp)) { Text( text = stringResource(id = R.string.long_text) ) } }
Notice the 2nd column layout with a Spacer
where we tell the Spacer
to .fillMaxHeight()
If the .height(intrinsicSize = IntrinsicSize.Max)
on the Row
was not set, the Spacer
would take up the entire parent’s height (entire screen height in this case):
Setting intrinsicSize.Max
on the Row
allows us to query the tallest column’s height (3d column) and use the value to set the 2nd column’s height.
You can use IntrinsicSize.Min
or IntrinsicSize.Max
and it can apply to height
or width
. The documentation on Intrinsic measurements contains more examples.