Modifier.wrapContentWidth() vs Modifier.width(IntrinsicSize.Max) in Android Jetpack Compose

Viewed 2758

Let's say I want to create a Column which is as wide as the widest child Text inside it. For this purpose the column can use .wrapContentWidth() modifier or .width(IntrinsicSize.Max), but the result looks the same. What is the difference between these two modifiers? For example:

Column(
    modifier = Modifier.wrapContentWidth()
//  modifier = Modifier.width(IntrinsicSize.Max)
) {
    Text("short text", Modifier.background(Color.LightGray))
    Text("some longer text", Modifier.background(Color.LightGray))
}

enter image description here enter image description here

1 Answers

Let's add a Divider between the texts. We want the divider to be as wide as the widest text.

Column(
    modifier = Modifier.wrapContentWidth()
//  modifier = Modifier.width(IntrinsicSize.Max)
) {
    Text("short text", Modifier.background(Color.LightGray))
    Divider(color = Color.Red)
    Text("some longer text", Modifier.background(Color.LightGray))
}

enter image description here enter image description here

As you see, in case of Modifier.wrapContentWidth() the divider forces the column to be as wide as its parent. It happens because Divider uses .fillMaxWidth() under the hood and since the column's .wrapContentWidth() doesn't constraint its children width, the divider expands as much as it can.

In the same time Modifier.width(IntrinsicSize.Max) behaves as we'd expected. The divider doesn't occupy space if no constraints are given, so it's intrinsic width is 0 and it doesn't affect the column width.

Related