【问题标题】:How to create MultiChoiceGrid with Jetpack Compose?如何使用 Jetpack Compose 创建多选网格?
【发布时间】:2021-08-19 14:01:56
【问题描述】:

我想创建类似于 Google 表单的 MultiChoiceGrid, 每个选项的顶部都有列标题,前面有问题的 RadioButton 行,但不知道该怎么做。

谁能给我一个例子,或者有什么布局吗?

Form that I want

【问题讨论】:

    标签: android android-jetpack-compose


    【解决方案1】:

    要存储选择状态,您可以使用MutableListState,在state documentation 中查看更多信息

    要显示它 - LazyVerticalGrid,请在 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)
            )
        }
    }
    


    如果你想为列/行添加标题,你可以在里面添加更多的项目,你只需仔细计算=)

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

    【讨论】:

    • 我已经编辑了我的问题。 @Philip 你能再检查一下吗?
    猜你喜欢
    • 2020-02-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-23
    • 2022-08-22
    • 1970-01-01
    • 1970-01-01
    • 2021-08-12
    相关资源
    最近更新 更多