Box Layout in Jetpack Compose
Box Layout in Jetpack Compose
Box is a foundational layout composable in Jetpack Compose that stacks its children on top of each other within a common parent. Unlike Column and Row, which arrange children sequentially along a single axis, Box overlays children in a back to front order. This makes it the primary tool for layering UI elements such as placing text over images, adding floating action buttons, or building custom overlay effects. By the end of this lesson, you will be able to:
- Explain how
Boxstacks children and how drawing order is determined. - Use
contentAlignmentto control the default position of all children. - Apply
Modifier.align()on individual children to override the parent alignment. - Identify practical use cases where
Boxis preferred overColumnorRow.
How Box Stacks Children
Box places its children in the order they are declared. The first child is drawn at the bottom of the stack, and each subsequent child is drawn on top. This layering behavior is similar to FrameLayout in the traditional View system.
@Composable
fun LayeredBox() {
Box(modifier = Modifier.size(200.dp)) {
Box(
modifier = Modifier
.fillMaxSize()
.background(Color.Blue)
)
Box(
modifier = Modifier
.size(100.dp)
.background(Color.Red)
)
}
}
In this example, the blue box fills the entire 200dp area, and the red box is drawn on top at 100dp. Both default to the top start corner unless alignment is specified.
Controlling Alignment
The contentAlignment parameter sets the default alignment for all children within the Box. Individual children can override this default using Modifier.align().
@Composable
fun ImageWithOverlay() {
Box(
modifier = Modifier.size(200.dp),
contentAlignment = Alignment.BottomCenter
) {
Image(
painter = painterResource(id = R.drawable.background),
contentDescription = "Background Image"
)
Text(
text = "Overlay Text",
color = Color.White,
modifier = Modifier
.background(Color.Black.copy(alpha = 0.5f))
.padding(8.dp)
)
}
}
This interview continues for subscribers
Subscribe to Dove Letter for full access to exclusive interviews about Android and Kotlin development.
Become a Sponsor