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

orangy

06/15/2022, 7:17 PM
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

Zach Klippenstein (he/him) [MOD]

06/18/2022, 1:38 AM
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

orangy

06/18/2022, 11:28 AM
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

Zach Klippenstein (he/him) [MOD]

06/29/2022, 3:18 AM
Yep, sounds right. i believe if you measure yourself less than min constraints you get centered.
2 Views