如何根据数据类属性更新lazyColumn项目的颜色?
首先,itemBackgroundColor
是正确的,有些项目是蓝色的,有些是灰色的。
但是当列表更新并且某些 item.judge
发生变化时,itemBackgroundColor
将不会相应更新。
当 list
更新时,如何更新 itemBackgroundColor
?多谢!
@Composable
fun LayoutsCodelab(viewModel: MyViewModel) {
// list<Item>, Item contains name, judge
val list = viewModel.myList.observeAsState(listOf()).value
Scaffold {
LazyColumn(state = rememberLazyListState()) {
items(list.size) {
val item = list[it]
// How can I update itemBackgroundColor based on item.judge?
val itemBackgroundColor by mutableStateOf(
if (item.judge) Color.Blue else Color.Gray)
// apply itemBackgroundColor here
Row(modifier = Modifier.background(color = itemBackgroundColor)) {
//other detail codes ...
}
}
}
}
}
At first, itemBackgroundColor
is correct, some items are blue and some are gray.
But when the list is updated and some item.judge
changed, itemBackgroundColor
won't update accordingly.
How can I update itemBackgroundColor
when the list
is updated? Thanks a lot!
@Composable
fun LayoutsCodelab(viewModel: MyViewModel) {
// list<Item>, Item contains name, judge
val list = viewModel.myList.observeAsState(listOf()).value
Scaffold {
LazyColumn(state = rememberLazyListState()) {
items(list.size) {
val item = list[it]
// How can I update itemBackgroundColor based on item.judge?
val itemBackgroundColor by mutableStateOf(
if (item.judge) Color.Blue else Color.Gray)
// apply itemBackgroundColor here
Row(modifier = Modifier.background(color = itemBackgroundColor)) {
//other detail codes ...
}
}
}
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,除非您的用例严格要求,否则不要使用 LiveData。
在您的 ViewModel 中,您可以像这样创建一个列表,
然后,在您的活动中,您可能不应该传递整个视图模型,但这完全取决于您。因此,在这种情况下,
您不需要在原始代码中调用
mutableStateOf
的地方使用它。请考虑使用 State-in-Compose Codelab 来进一步学习。另外,我认为如果项目是按照更新的列表呈现的,即使没有这些修改,您的代码实际上也应该可以正常工作,但问题(我确信大约 2/3)可能在于“其他代码详细信息... ”部分,其中存在的可组合项可能会占用
item
的整个空间,因此隐藏其修改后的背景。考虑将此背景修改器也应用到那里的子可组合项,然后检查它是否有效。First of all, refrain from using
LiveData
unless your use-case strictly requires so.Inside your
ViewModel
, you can create a list like so,Then, inside your activity, you should probably not pass the entire viewmodel around, but that's totally up to you. So, in this case
You do not require
mutableStateOf
's usage at the place where you were calling it in your original code. Consider taking the State-in-Compose codelab to learn further.Also, I think your code should have actually worked fine even without these modifications if the items were being rendered as per the updated list, but the problem (I am about 2/3 sure) may lie in the "other code details..." section, where the Composables present there may be taking up the entire space of the
item
, hence, hiding it's modified background. Consider applying this background Modifier to the children Composables over there as well and then check it is works out.