var courses by rememberSaveable { mutableStateOf(mutableListOf<String>()) }
val physiotherapy = stringResource(R.string.physiotherapy)
val chemotherapy = stringResource(R.string.chemotherapy)
val biology = stringResource(R.string.biology)
val political = stringResource(R.string.political)
val history = stringResource(R.string.history)
val geography = stringResource(R.string.geography)
val courseList = listOf(physiotherapy, chemotherapy, biology, political, history, geography)
courseList.forEachIndexed { _, s ->
FilterChip(
selected = s in courses,
leadingIcon = {
AnimatedVisibility(visible = s in courses) {
Icon(
imageVector = Icons.Rounded.Done,
contentDescription = stringResource(R.string.selected)
)
}
},
onClick = {
courses.apply {
if (s in this) {
remove(s)
} else {
add(s)
}
}
},
label = { Text(text = s) }
)
}
这是我使用 Jetpack Compose 所写的一段代码,这段代码在一个弹窗里,就是一个高中生选科的功能,但是 FilterChip 被点击后,不会实时更新,只有在再次打开弹窗后才会生效,求解
不知道你这个问题是否已经解决, 如果还没有解决的话:这个问题可以通过使用remember
和mutableStateListOf
解决。下面是具体的解决方案:
首先,确保你已经在项目中引入了androidx.compose.runtime
和androidx.compose.runtime.livedata
依赖。
使用remember
来保存选科的状态,该状态将在组合函数重新计算时保持不变。例如,你可以在调用函数中使用remember
来保存一个mutableStateListOf
:
kotlin val selectedSubjects = remember { mutableStateListOf<String>() }
kotlin FilterChip( label = { Text(subject) }, selected = selectedSubjects.contains(subject), onSelectedChange = { isSelected -> if (isSelected) { selectedSubjects.add(subject) } else { selectedSubjects.remove(subject) } } )
当点击 FilterChip 时,会根据是否已选中来添加或删除相应的科目。
selectedSubjects
列表过滤你的数据,并在弹窗内容中更新。```kotlin val filteredData = data.filter { item -> selectedSubjects.any { it == item.subject } }
// 在弹窗中使用 filteredData ```
这样,当你点击 FilterChip 时,选科结果将实时更新。确保在弹窗中使用filteredData
来展示经过筛选的数据。
希望以上解决方案对你有帮助。如果你还有其他问题,请随时提问。