我正在寻找有关如何使用不同可组合项中的按钮清除惰性列组合中的所有复选框的解决方案。
所以我想要做的就是可以选中 ObjectComposable 下的 ParentItemComposable 中的一个或多个复选框。然后能够使用 ClearAllButton 可组合项清除所有选择
这是我在下面尝试过的代码
@Composable
fun ParentItemComposable(
reload: Boolean,
viewModel: EtfFilterViewModel,
modifier: Modifier = Modifier
) {
val itemsList by remember {
mutableStateOf(etfFilterViewModel.getEParentList)
}
Column() {
LazyColumn(
Modifier
.background(color = PaleGrey50)
.padding(bottom = 80.dp)
) {
items(itemsList.sortedBy { it.title }) { parentItem ->
val title: String = when (parentItem.title) {
"geography" -> {
"Geography"
}
"assetClass" -> {
"Asset Class"
}
"focusStyle" -> {
"Focus / Style"
}
else -> {
"Other"
}
}
Box(
modifier = Modifier
.padding(0.dp, 0.dp, 0.dp, 5.dp)
.fillMaxWidth()
.background(color = White)
) {
Text(
text = title,
modifier = Modifier.padding(5.dp),
style = MaterialTheme.typography.h6
)
}
Column(modifier = Modifier.padding(start = 16.dp)) {
parentItem.filterObjectList.sortBy {
it.name
}
parentItem.filterObjectList.forEach { filterObject ->
ObjectComposable(
filterObject,
viewModel,
itemsList.indexOf(parentItem),
parentItem.filterObjectList.indexOf(filterObject),
)
}
parentItem.filterObjectList.filter { i -> i.isChecked }
}
}
}
}
}
@Composable
private fun ObjectComposable(
filterObject: FilterObject,
viewModel: ViewModel,
…..
) {
Row(
verticalAlignment = Alignment.CenterVertically
) {
val checkedState = remember { mutableStateOf(false) }
val context = LocalContext.current
Checkbox(
checked = checkedState.value,
onCheckedChange = {
checkedState.value = it
….
viewModel.updateFilteredListOfStrings(filterObject.name)
},
enabled = true,
modifier = Modifier.padding(end = 8.dp)
)
Text(text = efilterObjectname)
}
}
@Composable
fun ClearAllButton(
onButtonClick: () -> Unit,
modifier: Modifier = Modifier,
) {
Row(
verticalAlignment = Alignment.Bottom
) {
Button(
onClick = { onButtonClick() },
modifier = Modifier
.wrapContentHeight()
.fillMaxWidth()
.padding(16.dp),
contentPadding = PaddingValues(16.dp),
colors = ButtonDefaults.buttonColors(
backgroundColor = PaleGrey50,
contentColor = Secondary
),
border = BorderStroke(1.dp, color = Secondary),
shape = RoundedCornerShape(4.dp),
) {
Text(
text = stringResource(R.string.clear_all),
fontSize = FontSize.Small,
fontWeight = FontWeight.Bold,
)
}
}
}
我期望的是 ClearAllButton 可组合项将清除在 ParentItemComposable lazycolum 中选中的所有复选框
您可以在 viewModel 中使用 MutableStateList 来保存包含 checkBox 观察到的布尔变量的数据实体。然后您可以通过调用 Kotlin 数据类的 copy 方法来迭代列表并修改其项目。