Hi, I try to render a blue rectangle with fixed wi...
# compose
j
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
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
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
May I know where is the source code defining this behavior? I try to trace the source code but not found.
m
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
Nice, thanks for your explanation.