Hi, how can I position a composable view at a perc...
# compose
p
Hi, how can I position a composable view at a percentage height of a composable container view? For example, centering a Text at the 20% of the height of its container.
p
thank you, it seems too much complex, does not exist something lighter for simply specifying the y position in a percentage of the height of the parent for example?
z
Isn’t this what BoxWithConstraints is for?
c
I’ve sometimes approached this with Spacers like this
Copy code
@Composable
fun Thing() {
    Column(Modifier.fillMaxHeight()) {
        Spacer(Modifier.fillMaxHeight(0.2f))
        Text("Hello")
    }
}
p
@Zun can you show me a sample of doing that with BoxWithConstraints?
@Chris Sinco [G] good idea
p
You can try:
Copy code
.onGloballyPositioned
I believe it works with any LayoutNode but you could use it with BoxConstraints too. In the link bellow I played with it a little bit, there is an animation commented out that you can uncomment to see how the offset gets animated. https://github.com/pablichjenkov/ComposeStudy/blob/04298ca8393d3eea0f5b7883fb22316[…]/app/src/main/java/com/pablichj/study/compose/home/HomePage2.kt
The downside of using .onGloballyPositioned is that you do 2 layout passes, the first one when the element has no position and then the second one using the position from the first layout. But a similar problem you will find in LayoutNodes that use
subComposition
. I mean, if we can call this a problem at this point, it seems that one or 2 more recompositions is not a big performance deal
k
Use a tool that is the most appropriate for a job. Globally positioned modifier and box with constraints come with performance overhead. The right tool is either spacers or a very simple custom layout.
p
custom layout is awesome, the compose api is way easier than the inherit View/ViewGroup method used in the ViewTree system pre-compose.
835 Views