Home > Blockchain >  Jetpack compose: position elements inside a Box
Jetpack compose: position elements inside a Box

Time:04-25

I have a Box in my app with a bunch of children:

Box(modifier = Modifier.fillMaxSize()) {
    Text("a")
    Text("b")
}

I want the text to appear aligned to the top at 20% distance from the start. How do I achieve that?

CodePudding user response:

To solve this you need two parts:

  1. There're two ways to layout Box content: contentAlignment will apply alignment for all children, and Modifier.align, which can be applied for a specific child.

  2. Usually you can use Modifier.padding in such cases, but not in case when you need relative size. The easiest way to take part of parent size is using Modifier.fillMax..., modifier, in this case Modifier.fillMaxWidth(0.2f) can be applied to a Spacer, placed in a Row with your element.

Box(modifier = Modifier.fillMaxSize()) {
    Row(
        Modifier
            .align(Alignment.TopStart)
    ) {
        Spacer(Modifier.fillMaxWidth(0.2f))
        Text("a")
    }
}

CodePudding user response:

Use the offset/absoluteOffset modifiers along with BoxWithConstraints.

  • Related