【问题标题】:How to change the drawing order of a layout children in Android Jetpack Compose?如何在 Android Jetpack Compose 中更改布局子项的绘制顺序?
【发布时间】:2021-01-27 16:28:30
【问题描述】:

默认情况下,在 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参数强制将船拖到水下吗?

【问题讨论】:

    标签: android android-jetpack android-jetpack-compose


    【解决方案1】:

    你可以使用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 参数会影响绘制顺序:

    【讨论】:

    • 我真的很喜欢这个关于船的答案
    【解决方案2】:

    只需将 Box 包装在 if 语句中,并为 if 和 else 块分别创建两个框。没坏处

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-12-16
      • 1970-01-01
      • 2021-07-22
      • 1970-01-01
      • 2022-07-08
      • 1970-01-01
      相关资源
      最近更新 更多