Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jetpack compose: position elements inside a Box

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?

like image 345
thewolf Avatar asked Jun 08 '26 13:06

thewolf


2 Answers

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")
    }
}
like image 50
Philip Dukhov Avatar answered Jun 10 '26 03:06

Philip Dukhov


follow thewolf's answer

I found this solution.

Let's check this code and the blue box below.

@Composable
fun BoxExample() {
    BoxWithConstraints {
        val boxWithConstraintsScope = this
        val yOffset = 0.2 * boxWithConstraintsScope.maxHeight.value

        Box(
            modifier = Modifier
                .fillMaxSize()
        ) {

            Box(
                modifier = Modifier
                    .height(300.dp)
                    .width(300.dp)
                    .background(Color.Red)

            )
            Box(
                modifier = Modifier
                    .height(200.dp)
                    .width(200.dp)
                    .background(Color.Green)
            )
            Box(
                modifier = Modifier
                    .offset(y =  yOffset.dp)
                    .height(100.dp)
                    .width(100.dp)
                    .background(Color.Blue)
            )
        }
    }
}

Look at Blue box

like image 21
Kiều Phong Avatar answered Jun 10 '26 02:06

Kiều Phong



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!