Natdanai Chaiyakan
Natdanai Chaiyakan

Reputation: 13

How to create MultiChoiceGrid with Jetpack Compose?

I want to create MultiChoiceGrid that look similar to Google Form, having column header in the top of each choice, and row of RadioButton with question in the front, but don't know how to do it.

Can anyone give me an example, or is there any layout for this?

Form that I want

Upvotes: 1

Views: 390

Answers (1)

Phil Dukhov
Phil Dukhov

Reputation: 88297

To store selection state you can use MutableListState, check out more in the state documentation

And to display it - LazyVerticalGrid, check out more in the lists documentation

val selectionState = remember {
    List(100) { false }
        .toMutableStateList()
}
LazyVerticalGrid(cells = GridCells.Fixed(10)) {
    itemsIndexed(selectionState) { i, selected ->
        Checkbox(
            checked = selected,
            onCheckedChange = { selectionState[i] = it },
            colors = CheckboxDefaults.colors(checkmarkColor = Color.Blue)
        )
    }
}


If you wanna add titles for columns/rows, you can more items inside, you just calculate carefully =)

val columnTitles = List(4) { "Column $it" }
val rowTitles = List(10) { "Player $it" }
val rowTitleWidth = 50.dp
val selectionState = remember {
    List(rowTitles.count()) {
        List(columnTitles.count()) { false }
            .toMutableStateList()
    }.toMutableStateList()
}
LazyVerticalGrid(cells = GridCells.Fixed(columnTitles.count() + 1)) {
    item {
        // top left empty cell
        Spacer(modifier = Modifier.width(rowTitleWidth))
    }
    items(columnTitles) { columnTitle ->
        Text(columnTitle)
    }
    rowTitles.forEachIndexed { i, rowTitle ->
        item {
            Box(
                modifier = Modifier
                    .width(rowTitleWidth)
            ) {
                Text(
                    rowTitle,
                )
            }
        }
        items(columnTitles.count()) { j ->
            Checkbox(
                checked = selectionState[i][j],
                onCheckedChange = { selectionState[i][j] = it },
                colors = CheckboxDefaults.colors(checkmarkColor = Color.Blue),
            )
        }
    }
}

Upvotes: 3

Related Questions