Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 207
Yannick Avatar asked Jan 28 '21 17:01

Yannick


3 Answers

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

like image 169
Gabriele Mariotti Avatar answered Sep 23 '22 01:09

Gabriele Mariotti


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

like image 26
Yannick Avatar answered Sep 25 '22 01:09

Yannick


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))
}
like image 34
Amirhosein Avatar answered Sep 23 '22 01:09

Amirhosein