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?
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")
}
}
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
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))
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With