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

mgrazianodecastro

02/27/2023, 7:24 PM
how does one set padding by % relative to the parent size?
f

Francesc

02/27/2023, 7:26 PM
You could create a
layout
modifier where you set the constraints for the content as the incoming constraints, minus whatever padding you want, which can be a percentage of the incoming constraints
m

mgrazianodecastro

02/27/2023, 7:29 PM
hmm I may need a simpler solution, since I need the padding in a lazy row
horizontalArrangement = Arrangement.spacedBy(x)
, for example
well,I guess I'm gonna use a BoxWithConstraints and calculate on the children
f

Francesc

02/27/2023, 7:33 PM
Copy code
@Preview(widthDp = 360, heightDp = 420)
@Composable
fun PercentPadding() {
    Box(
        modifier = Modifier
            .fillMaxSize()
            .background(Color.Red)
    ) {
        Box(
            modifier = Modifier
                .layout { measurable, constraints ->
                    val marginPercent = 10
                    val widthPadding = constraints.maxWidth * marginPercent / 100
                    val heightPadding = constraints.maxHeight * marginPercent / 100
                    val childConstraints = constraints.copy(
                        maxWidth = constraints.maxWidth - 2 * widthPadding,
                        maxHeight = constraints.maxHeight - 2 * heightPadding,
                    )
                    val placeable = measurable.measure(childConstraints)
                    layout(
                        width = placeable.width,
                        height = placeable.height
                    ) {
                        placeable.placeRelative(
                            x = widthPadding,
                            y = heightPadding,
                        )
                    }
                }
                .fillMaxSize()
                .background(Color.Blue)
        )
    }
}
m

mgrazianodecastro

02/27/2023, 7:36 PM
yeah, for the start / end of a lazy list it won't work, since the list padding does not constraint the content
c

Chris Sinco [G]

02/27/2023, 11:59 PM
You may be able to use a Spacer and pass a fractional float to fillMaxWidth/Height, which should end up being a percentage of its parent’s width/height
m

mgrazianodecastro

02/28/2023, 2:07 PM
that does also work, but I kind of hate to even have something else in a lazy list besides the the "actual" content. Imagine doing some snapshots callback and having to account for that extra spacer. Either way, thanks
13 Views