Yannick
Yannick

Reputation: 5861

Match Width of Parent in Column (Jetpack Compose)

By default, Column {} has the width of it's largest child element. How can I make all other elements to fit the width of the parent Column? If I use Modifier.fillMaxWidth() the elements will take up the entire available space and make the parent Column larger. How can I achieve the same behavior like a Modifier.matchParentWidth() Modifier would provide?

Upvotes: 89

Views: 95982

Answers (7)

Thracian
Thracian

Reputation: 66516

Since this question is not only about matching Text Composables which return intrinsic sizes via Modifier's

@Stable
fun Modifier.width(intrinsicSize: IntrinsicSize) = when (intrinsicSize) {
    IntrinsicSize.Min -> this.then(MinIntrinsicWidthModifier)
    IntrinsicSize.Max -> this.then(MaxIntrinsicWidthModifier)
}

Then inside MaxIntrinsicWidthModifier with

override fun IntrinsicMeasureScope.maxIntrinsicWidth(
    measurable: IntrinsicMeasurable,
    height: Int
) = measurable.minIntrinsicWidth(height)

However, Intrinsic measurements don’t really measure the children twice. Instead, they do a different kind of calculation — you can think of it as a pre-measure step without requiring exponential measurement time, as it is cheaper and easier. So while this doesn’t exactly break the single measurement rule, it does bend it a little bit and shows a Compose requirement that falls outside of the usual ones.

When creating a custom layout, Intrinsics provide a default implementation based on approximations. However, in some cases, the default calculation might not work for you as intended, so the API provides a way of overriding these defaults.

To specify the Intrinsic measurements of your custom layout, you can override the minIntrinsicWidth, minIntrinsicHeight, maxIntrinsicWidth, and maxIntrinsicHeight of the MeasurePolicy interface during the measurement pass:

If you encounter such cases

https://medium.com/@lepicekmichal/compose-intrinsic-redraw-bug-2cdecef0f96c

Row IntrinsicSize.Min not working when the children are async loading images

Android Jetpack Compose Row's height (IntrinsicSize.Min) is not stretched when children column generate more composables

Or If you use a parent with IntrinsicSize while any of content Composables are BoxWithConstratins, lazy lists, TabRow or etc. you get exception.

Asking for intrinsic measurements of SubcomposeLayout layouts is not supported. This includes components that are built on top of SubcomposeLayout, such as lazy lists, BoxWithConstraints, TabRow, etc.

In that case if you know which child will be bigger you can measure it inside a Layout first then measure rest using its width.

If any of these child composable can be widest you need to use SubcomposeLayout as in this question.

Jetpack Compose set sibling Composables' width to longest one dynamically with SubcomposeLayout

Upvotes: 0

k4dima
k4dima

Reputation: 6251

Surface(
    modifier = Modifier
        .fillMaxSize()
        .wrapContentWidth(Alignment.CenterHorizontally)
        .wrapContentHeight(Alignment.CenterVertically)
) {
    Column(
        modifier = Modifier.width(300.dp)
    ) {
        // ...
        Button(
            { /*TODO*/ },
            modifier = Modifier
                .fillMaxWidth()
                .height(60.dp)
        ) {
            Text(stringResource(R.string.log_in))
        }
    }
}

enter image description here

Upvotes: 4

Yannick
Yannick

Reputation: 5861

The solution is to leverage the power of intrinsic measurements.

Instead of using Modifier.fillMaxWidth() we use width(IntrinsicSize.Min) to match the width to the minimum width of the largest element

Upvotes: 72

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363439

You can use the Modifier .width(IntrinsicSize.Max)

 Column(Modifier.width(IntrinsicSize.Max)) {
        Box(Modifier.fillMaxWidth().background(Color.Gray)) {
            Text("Short text")
        }
        Box(Modifier.fillMaxWidth().background(Color.Yellow)) {
            Text("Extremely long text giving the width of its siblings")
        }
        Box(Modifier.fillMaxWidth().background(Color.Green)) {
            Text("Medium length text")
        }
    }

enter image description here

Upvotes: 122

Deepak Das
Deepak Das

Reputation: 183

you can simply use fillMaxWidth()

 Row(modifier = Modifier
        .fillMaxWidth()
        .background(Color.Cyan),) {
        Spacer(modifier = Modifier.padding(start = 4.dp))
        Image(
            painter = painterResource(R.drawable.tom_jerry),
            contentDescription ="this is image",

            modifier = Modifier
                .size(40.dp)
                .clip(shape = CircleShape).align(CenterVertically),
            alignment = Alignment.Center,
            contentScale = ContentScale.FillHeight


        )
        Column(modifier = Modifier.padding(start = 10.dp)) {
            Text(text = "Name : ${msg.name}")
            Text(text = "age : ${msg.age.toString()}")

        }

enter image description here

Upvotes: 4

Rafsanjani
Rafsanjani

Reputation: 5443

You are applyingModifier.width(300.dp) onto the parent column, the maximum width a child item in that column can occupy is 300.dp.

Using Modifier.fillMaxWidth() on your Text composable in this context is synonymous to using Modifier.preferredWidth(300.dp) because it can only get as wide as it's parent composable.

Upvotes: -2

Rainbow_62
Rainbow_62

Reputation: 1297

Here I'm using Modifier.fillMaxWidth and the items doesn't make parent column larger :

@Composable
fun Demo() {
Column(modifier = Modifier.width(300
    .dp)) {
    Text(text = "with fillMaxWidth modifier",modifier = Modifier.fillMaxWidth().background(Color.Red))
    Text(text = "without fillMaxWidth modifier",modifier = Modifier.background(Color.Gray))
 }

}

What I usually do to achieve the matchParentWidth is something like this (It's dirty but gets the job done):

val context = AmbientContext.current.resources
val displayMetrics = context.displayMetrics
val scrWidth = displayMetrics.widthPixels / displayMetrics.density

Column(modifier = Modifier.width(300
    .dp)) {
    Text(text = "with fillMaxWidth modifier",modifier = Modifier.fillMaxWidth().background(Color.Red))
    Text(text = "without fillMaxWidth modifier",modifier = Modifier
        .preferredWidth(scrWidth.dp)
        .background(Color.Gray))
}

Upvotes: 6

Related Questions