How to change the drawing order of a layout children in Android Jetpack Compose?

Viewed 5080

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?

2 Answers

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:

enter image description here enter image description here

Just wrap the Box in an if statement and create two boxes each for the if and the else block. It is no harm

Related