By default in Jetpack Compose a layout children rendering order matches the order of the children in the code. In the following example the ship (Text) will be drawn over the water (Box).
@Composable
fun DrawingOrderExample(submarineMode: Boolean) {
Box(contentAlignment = Alignment.Center) {
Box(
modifier = Modifier
.size(32.dp)
.background(Color.Cyan.copy(alpha = .5f))
)
Text("⛵")
}
}
Can I force the ship to be drawn under the water according to submarineMode
argument?
Layouts are the building blocks to design the UI. In the traditional Android development, we have RelativeLayout, LinearLayout, FrameLayout, ConstraintLayout, etc. Likewise, Jetpack Compose offers four types of layouts at the moment:
You will need to install Android Studio Canary, Arctic Fox (2020.3.1) version to use the Jetpack Compose beta. Layouts are the building blocks to design the UI. In the traditional Android development, we have RelativeLayout, LinearLayout, FrameLayout, ConstraintLayout, etc. Likewise, Jetpack Compose offers four types of layouts at the moment:
Note: Compose handles nested layouts efficiently, making them a great way to design a complicated UI. This is an improvement from Android Views, where you need to avoid nested layouts for performance reasons. To set children's position within a Row, set the horizontalArrangement and verticalAlignment arguments.
The modifier design makes this kind of behavior explicit and predictable, and gives you more control to achieve the exact behavior you want. It also explains why there is not a margin modifier but only a padding one. Jetpack Compose provides a list of built-in modifiers to help you decorate or augment a composable.
You can use zIndex() modifier to change the children drawing order:
...
import androidx.compose.ui.zIndex
Box {
Text("Drawn second", Modifier.zIndex(1f))
Text("Drawn first")
}
The ship example:
@Composable
fun DrawingOrderExample(submarineMode: Boolean) {
Box(contentAlignment = Alignment.Center) {
Box(
modifier = Modifier
.size(32.dp)
.background(Color.Cyan.copy(alpha = .5f))
)
val shipZIndex = if (submarineMode) -1f else 1f
Text(
text = "⛵",
modifier = Modifier.zIndex(shipZIndex) // <- here's the trick
)
}
}
Now submarineMode
argument affects the drawing order:
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