MaxAstin
MaxAstin

Reputation: 613

How create grid view with merged cells in Compose?

I need to implement next grid:

enter image description here

Size of red boxes should depend on screen width. I tried use Column and Rows:

@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))
            }
        }
    }
}

But since I have one less space in second row, it doesn't looks perfect.

enter image description here

How I can create pixel perfect grid view with merged cells? I know about LazyGrid, but I'm not sure if it's appropriate since my grid needs to be full screen.

Upvotes: 5

Views: 564

Answers (1)

Gabriele Mariotti
Gabriele Mariotti

Reputation: 363439

You can specify the column span with the span parameter of the LazyGridScope DSL item and items methods.

Something like:

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)))
    }
}

enter image description here

Upvotes: 8

Related Questions