https://kotlinlang.org logo
#compose
Title
# compose
f

Fudge

07/27/2020, 7:05 PM
Consider the Box:
Copy code
Box(backgroundColor = Color.Blue) {
   Text("Foo")
}
Without specifying any height or width constraints, the
Box
will automatically size to be the size of the Text (picture 1). Now, consider picture 2. The text
Foo
is not a child of the left box, or the right one. Therefore a possible implementation of that would use a
Stack
.
Copy code
Stack {
        Row {
            Box(Modifier.weight(1f).fillMaxWidth(), backgroundColor = Color.Blue)
            Box(Modifier.weight(1f).fillMaxWidth(), backgroundColor = Color.Red)
        }
        Text(text = "foo", textAlign = TextAlign.Center, modifier = Modifier.fillMaxWidth())
    }
The problem now though, is that
Box
has no children, and would have a height of 0. Here's another attempt using `ConstraintLayout`:
Copy code
ConstraintLayout {
    val (left,right,text) = createRefs()
    Box(backgroundColor = Color.Blue, modifier = Modifier.weight(1f).constrainAs(left){
        linkTo(start = parent.start, end = right.start)
    })
    Box(backgroundColor = Color.Red,modifier = Modifier.weight(1f).constrainAs(right){
        linkTo(start = left.start, end = parent.end)
    })

    Text(text = "foo", modifier = Modifier.constrainAs(text){
        linkTo(start = left.start, end = right.end, bottom = left.bottom, top = left.top)
    })
}
This has the same reult as the
Stack
approach, with the boxes not showing at all. So how do I communicate to compose that the boxes should be at least the size of the text? The aim is to not hardcode constraints such as
Modifier.height()
.
m

matvei

07/27/2020, 7:19 PM
Even without children Box will obey the Modifier-based enforced sizes if you set them. In the example with
Row
, you set weight(1f) in both, which will stretch each box horizontally. However , you set no height-enforcing modifier so Boxes have 0 height. you need to replace fillMaxWidth with fillMaxHeight and that should do the trick
f

Fudge

07/27/2020, 7:39 PM
But that will fit the height too much, i want it to wrap around the text
So if the text is height of 20 it will also have height of 20
s

Sean McQuillan [G]

07/27/2020, 7:59 PM
I think you want
IntrinsicSize
based on the examples, though I may be misunderstanding the problem
Copy code
@ExperimentalLayout
@Composable
fun SizedBox() {
    Stack(modifier = Modifier.preferredHeight(IntrinsicSize.Min)) {
        Box(
            backgroundColor = Color.Yellow,
            modifier = Modifier
                .fillMaxSize()
        )
        Text("Hello", modifier = Modifier.fillMaxWidth())
    }
}
As the general pattern – Size the parent based on the intrinsic size, then fill it
f

Fudge

07/27/2020, 8:59 PM
I think that’s the one I’m looking for, thanks