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?
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?
Use the offset
/absoluteOffset
modifiers along with BoxWithConstraints
.
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)
)
}
}
}
Use the offset
/absoluteOffset
modifiers along with BoxWithConstraints
.
If you are working with DropdownMenus, the previous answers won't work with the resultant menus. DropDownMenus require something special as their menus don't honor the typical alignment instructions.
But I found that wrapContentSize(Alignment.some_alignment)
, an esoteric aspect of Modifier, seems to do the trick (although the documentation is beyond my comprehension).
This code will put both the icon and the menu itself at the top right of a Box that takes the whole screen width.
Box(
modifier = modifier
.fillMaxWidth()
.wrapContentSize(Alignment.TopEnd)
) {
MyDropdownIcon(...) { ... }
DropdownMenu(...) { ... }
}
Hope this helps some people--took me hours to figure this out.
© 2022 - 2025 — McMap. All rights reserved.