如何在 Compose 中创建包含合并单元格的网格视图?

Max*_*tin 5 android gridview android-jetpack-compose

我需要实现下一个网格:

在此输入图像描述

红色框的大小应取决于屏幕宽度。我尝试使用列和行:

@Composable
fun Component() {
    Column(modifier = Modifier.fillMaxWidth()) {
        Row {
            repeat(5) {
                if (it > 0) {
                    Spacer(modifier = Modifier.width(20.dp))
                }
                Box(modifier = Modifier
                    .aspectRatio(1f)
                    .weight(1f).background(Color.Red))
            }
        }
        Spacer(modifier = Modifier.height(20.dp))
        Row {
            repeat(4) {
                if (it > 0) {
                    Spacer(modifier = Modifier.width(20.dp))
                }
                val weight = if (it < 3) 1f else 2f
                Box(modifier = Modifier
                    .aspectRatio(weight)
                    .weight(weight).background(Color.Red))
            }
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

但由于第二排少了一个空间,所以看起来并不完美。

在此输入图像描述

如何使用合并单元格创建像素完美的网格视图?我了解 LazyGrid,但我不确定它是否合适,因为我的网格需要全屏。

Gab*_*tti 8

您可以使用LazyGridScope DSL和方法的参数指定列跨度spanitemitems

就像是:

val listgrid = (0 until 9).toList()

LazyVerticalGrid(
    columns = GridCells.Fixed(5),
    horizontalArrangement = Arrangement.spacedBy(16.dp),
    verticalArrangement = Arrangement.spacedBy(16.dp)
) {


    items(
        listgrid,
        span = { index ->
            val spanCount = if (index == 8) 2 else 1
            GridItemSpan(spanCount)
        }
    ) {
        Box(Modifier.size(50.dp).background(Red, RoundedCornerShape(4.dp)))
    }
}
Run Code Online (Sandbox Code Playgroud)

在此输入图像描述