如何在 Android Jetpack Compose 中更改布局子项的绘制顺序?
How to change the drawing order of a layout children in Android Jetpack Compose?
默认情况下,在 Jetpack Compose 中,布局子项的渲染顺序与代码中子项的顺序相匹配。在下面的示例中,船(文本)将绘制在水面上(框)。
@Composable
fun DrawingOrderExample(submarineMode: Boolean) {
Box(contentAlignment = Alignment.Center) {
Box(
modifier = Modifier
.size(32.dp)
.background(Color.Cyan.copy(alpha = .5f))
)
Text("⛵")
}
}
我能不能按照submarineMode
的说法强制把船拖到水下?
您可以使用 zIndex() 修改器来更改子项绘制顺序:
...
import androidx.compose.ui.zIndex
Box {
Text("Drawn second", Modifier.zIndex(1f))
Text("Drawn first")
}
船例:
@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
)
}
}
现在 submarineMode
参数影响绘制顺序:
只需将 Box 包裹在 if 语句中,然后分别为 if 和 else 块创建两个框。没关系
默认情况下,在 Jetpack Compose 中,布局子项的渲染顺序与代码中子项的顺序相匹配。在下面的示例中,船(文本)将绘制在水面上(框)。
@Composable
fun DrawingOrderExample(submarineMode: Boolean) {
Box(contentAlignment = Alignment.Center) {
Box(
modifier = Modifier
.size(32.dp)
.background(Color.Cyan.copy(alpha = .5f))
)
Text("⛵")
}
}
我能不能按照submarineMode
的说法强制把船拖到水下?
您可以使用 zIndex() 修改器来更改子项绘制顺序:
...
import androidx.compose.ui.zIndex
Box {
Text("Drawn second", Modifier.zIndex(1f))
Text("Drawn first")
}
船例:
@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
)
}
}
现在 submarineMode
参数影响绘制顺序:
只需将 Box 包裹在 if 语句中,然后分别为 if 和 else 块创建两个框。没关系