[英]Jetpack Compose: LazyColumn not updating with MutableList
I am trying to strikethrough a text at the click of a button using Jetpack Compose
but the UI is not updating .我正在尝试使用Jetpack Compose
单击按钮删除文本,但 UI未更新。
I have tried to set a button and on the click of a button, deletedTasks gets updated and if my task is in deletedTasks then it should show up with a strikethrough.我试图设置一个按钮并单击一个按钮, deletedTasks得到更新,如果我的任务在deletedTasks中,那么它应该显示一个删除线。
This change only happens manually but I want it to be automatic此更改仅手动发生,但我希望它是自动的
I am not sure how to go about this.我不确定如何与 go 联系。 This is my first time trying Jetpack Compose
, any help would be appreciated这是我第一次尝试Jetpack Compose
,任何帮助将不胜感激
@Composable
fun toDoItem(title: String, category: String, task: Task) {
val rememberTask = remember { mutableStateOf(deletedTasks) }
Surface(...) {
Column (...) {
Row {
Column (...) {
if (!deletedTasks.contains(task)){
Text(text = title, style = MaterialTheme.typography.h4.copy(
fontWeight = FontWeight.Bold
))
} else {
Text(text = title, style = MaterialTheme.typography.h4.copy(
fontWeight = FontWeight.Bold
), textDecoration = TextDecoration.LineThrough)
}
}
IconButton(onClick = {
rememberTask.value.add(task)
}) {
Icon(imageVector = Icons.Filled.Check, contentDescription = "Check")
}
}
}
}
}
@Composable
fun recyclerView(tasks: MutableList<Task>) {
LazyColumn (modifier = Modifier.padding(vertical = 10.dp, horizontal = 80.dp)) {
items(items = tasks) {task ->
toDoItem(task.title, task.category, task)
}
}
}
You are using MutableList<>
, which is not recommended for any collection use-cases in Jetpack Compose
.您正在使用MutableList<>
,不建议将其用于Jetpack Compose
中的任何集合用例。 I would advice changing it to a SnapshotStateList
.我建议将其更改为SnapshotStateList
。
Your recyclerView composable would look like this您的 recyclerView 可组合项看起来像这样
@Composable
fun recyclerView(tasks: SnapshotStateList<Task>) { ... }
and somewhere where you set things up (eg ViewModel
) would be like在你设置东西的地方(例如ViewModel
)就像
tasks = mutableStateListOf<Task>( ... )
Using SnapshotStateList
will guarantee an "update" or re-composition
with any normal list operation you do to it such as,使用SnapshotStateList
将保证“更新”或re-composition
您对它执行的任何正常列表操作,例如,
list.add( <new task> )
list.remove( <selected task> )
list[index] = task.copy()
<- idiomatic way of udpating a list list[index] = task.copy()
<- 更新列表的惯用方式There is also SnapshotStateMap
which is for Map key~value
pair use-case.还有用于Map key~value
对用例的SnapshotStateMap
。
But if you are curious as to how you would update your LazyColumn
with an ordinary List
, you would have to re-create the entire MutableList<Task>
so that it will notify the composer that an update is made because the MutableList<Task>
now refers to a new reference of collection of tasks.但是,如果您对如何使用普通List
更新LazyColumn
感到好奇,则必须重新创建整个MutableList<Task>
以便它会通知作曲家进行了更新,因为MutableList<Task>
现在引用任务集合的新引用。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.