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?
To solve this you need two parts:
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.
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")
}
}
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)
)
}
}
}

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