gpt4 book ai didi

android - Jetpack Compose 复选框未显示更改状态

转载 作者:行者123 更新时间:2023-12-04 23:53:54 28 4
gpt4 key购买 nike

我有一个用户将从中检查的专业列表。在用户对他们的选择感到满意后,我将收集所选复选框的信息并将这些专业保存在用户的个人资料中。
但是,当我点击任何复选框时, View 模型中的状态会发生变化,但复选框仍处于未选中状态。
专业列表

@Composable
fun SpecialtyList(
viewModel: SpecialtyListViewModel = hiltViewModel(),
navController: NavController
) {
LazyColumn(modifier = Modifier.fillMaxSize()) {
item {
viewModel.specialtyList.value.forEach { specialty ->
Row(
modifier = Modifier
.fillMaxWidth()
.padding(10.dp),
verticalAlignment = Alignment.CenterVertically
) {
Checkbox(
checked = specialty.isSelected,
onCheckedChange = {
specialty.isSelected = it
},
colors = CheckboxDefaults.colors(MaterialTheme.colors.primary)
)
Text(
text = specialty.name,
modifier = Modifier
.padding(horizontal = 10.dp)
)
}
}
}
}
}
专业查看型号
@HiltViewModel
class SpecialtyListViewModel @Inject constructor() : ViewModel() {

// HARD-CODED PROPERTIES
val specialtyList = mutableStateOf(
mutableListOf(
Specialty(name = "Emergency Medicine", isSelected = false),
Specialty(name = "Forensic Medicine", isSelected = false),
Specialty(name = "General Practitioner", isSelected = false)
)
}
专业型号
data class Specialty(
val name: String,
var isSelected: Boolean
)

最佳答案

为了 mutableStateOf要触发重组,应更新容器值,例如specialtyList = newValue .
它无法知道您已经更改了其中一个内部对象。
一般来说,data class是在函数式编程中使用不可变的好工具。如果你不使用 var在其中,您将排除许多错误。
使用 mutableStateListOf如果你的情况看起来更干净。在您的 View 模型中:

private val _specialtyList = mutableStateListOf(
Specialty(name = "Emergency Medicine", isSelected = false),
Specialty(name = "Forensic Medicine", isSelected = false),
Specialty(name = "General Practitioner", isSelected = false)
)
val specialtyList: List<Specialty> = _specialtyList

fun setSpecialtySelectedAtIndex(index: Int, isSelected: Boolean) {
_specialtyList[index] = _specialtyList[index].copy(isSelected = isSelected)
}
从您的可组合中使用它,如下所示:
viewModel.specialtyList.value.forEachIndexed { i, specialty ->
// ...
onCheckedChange = {
viewModel.setSpecialtySelectedAtIndex(i, it)
},
}
您可以在 documentation 中找到有关 Compose 中状态的更多信息。 ,包括 this youtube video它解释了基本原理。

关于android - Jetpack Compose 复选框未显示更改状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70040541/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com