Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

In Compose, how to set minimum height (minHeight) without consuming all available height?

In Jetpack Compose, I have a card composable that I want to be a minimum of 100.dp tall. However, if I use heightIn, the card consumes all available height up until the max. How do I set a minHeight without consuming all height?

Surface(
    modifier = heightIn(100.dp, 9999.dp),
) {
    // Content
}

To be clear, what I want is the following algorithm:

height = if (contentHeight > minHeight) {
    contentHeight 
} else {
    minHeight
}
like image 216
frodo2975 Avatar asked Sep 09 '25 17:09

frodo2975


2 Answers

Use Modifier.defaultMinSize

Surface(
    modifier = Modifier.defaultMinSize(minHeight = 100.dp),
) {
    // Content
}
like image 84
danartillaga Avatar answered Sep 13 '25 09:09

danartillaga


Edit

To be clear, what I want is the following algorithm:

height = if (contentHeight > minHeight) { contentHeight } else { minHeight }

Modifier.height(contentHeight.coerceAtLeast(minHeight)) is the shortened algorithm.

When a Layout measures and places children it checks constraints. You can find detail answered here about how it works.

For instance column has minHegith = 100.dp, while maxHeight is your composable height in dp. If it's root it's height of screen in dp

Column(modifier=Modifier.heightIn(min=100.dp)) {
   Box(modifier=Modifier.fillMaxSize().background(Color.Yellow))
}

For instance this Box covers whole space because it's min and max constraint is Column's maxHeight. In this case using Modifier.heightIn() won't limit, so you need Modifier.height() such as in my original answer with a fixed value or use custom layout to check and assign .

layout(width, height){} inside Layout.

But there is something to note with Surface that it forces minimum constraints to direct descendant, you can check my answer about Surface here.

Surface(modifier = Modifier.heightIn(min = 100.dp)) {
    Box(
        modifier = Modifier
            .size(300.dp)
            .background(Color.Yellow)
    )
}

This Box in example will cover all of the height because of being Surface's direct descendant.

Surface(modifier = Modifier.heightIn(min = 100.dp)) {
   Column() {
       Box(
           modifier = Modifier
               .size(300.dp)
               .background(Color.Yellow)
       )
   }
}

This one will have 300.dp size while Column covers all available space of Surface

like image 32
Thracian Avatar answered Sep 13 '25 07:09

Thracian