I’m trying to implement some custom `Layout`, and ...
# compose
o
I’m trying to implement some custom
Layout
, and somehow the content gets centered. I’ve measured this single item (image), placed it at (0,0) in a
layout
call with the size of the image (measured total children), and I expect it to be in the top left corner of the red area (parent size). Why is it in the center? Green rectangle depicts inner bounds of the parent, as if there was padding or something.
z
Can you share your code? Compose will automatically center something that declares its size to be bigger than the max constraints, but idk if that's what's happening here
o
An example would be primitive Row-like layout
Copy code
@Composable
fun TestLayout(
    modifier: Modifier,
    content: @Composable () -> Unit
) {
    Layout(content, modifier) { measurables, constraints ->

        val items = mutableListOf<Placeable>()
        val itemConstraints = constraints.copy(minWidth = 0, minHeight = 0)
        for (measurable in measurables) {
            val placeable = measurable.measure(itemConstraints)
            items.add(placeable)
        }
        val contentWidth = items.sumOf { it.width }
        val contentHeight = items.maxOf { it.height }
        layout(
            contentWidth,
            contentHeight
        ) {
            var x = 0
            items.forEach {
                it.place(x, 0)
                x += it.width
            }
        }
    }
}
And then usage
Copy code
TestLayout(Modifier.fillMaxWidth()) {
            Text("test")
        }
The text appears centered horizontally in the window. Looks like when
layout
is called with width/height less that constraints, it is centered. I wonder if it is by design. If I take min-constraints into equation, it works fine.
Copy code
layout(
            kotlin.math.max(constraints.minWidth, contentWidth),
            kotlin.math.max(constraints.minHeight, contentHeight)
        ) { … }
z
Yep, sounds right. i believe if you measure yourself less than min constraints you get centered.