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

Joseph Cheng

01/19/2020, 1:50 PM
Hi, I try to render a blue rectangle with fixed width and height, but it always fill the parent.
Copy code
setContent {
            MaterialTheme {
                ColoredRect(color = Color.Blue, width = 100.dp, height = 50.dp)
            }
        }
But once I put a
Container
as the parent, it works as expected. May I know why?
Copy code
setContent {
            MaterialTheme {
                Container {
                    ColoredRect(color = Color.Blue, width = 100.dp, height = 50.dp)
                }
            }
        }
k

Klaas Kabini

01/19/2020, 4:08 PM
From what I observed is that if DrawShape or DrawImage is wrapped inside a Container that is the root of a composable function then compose will assume that the shape or image is a background and make it fill ignoring the dimensions parameters you specified. This looks like it was by design and not a bug.
m

Mihai Popa

01/20/2020, 11:31 AM
Yep, the root of the layout hierarchy will need to fill all available space. When you add the
Container
this will fill the screen and the ColoredRect will be able to use its desired size
j

Joseph Cheng

01/20/2020, 4:32 PM
May I know where is the source code defining this behavior? I try to trace the source code but not found.
m

Mihai Popa

01/20/2020, 5:11 PM
This behavior comes from the View system - this will
onMeasure
the
AndroidComposeView
with
MeasureSpec.EXACTLY
which we then translate to fixed constraints in the Compose hierarchy, determining the root of the layout hierarchy to be forced due to constraints to fill the whole screen
Then you can see in
Container.kt
that it will looseMin the constraints before measuring its children, so its children will not be forced anymore to fill the whole screen
j

Joseph Cheng

01/21/2020, 5:43 PM
Nice, thanks for your explanation.
2 Views