0

起初,itemBackgroundColor是正确的,有些项目是蓝色的,有些是灰色的。

但是当列表更新并且有些item.judge改变时,itemBackgroundColor不会相应地更新。

itemBackgroundColor更新时如何list更新?非常感谢!

@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 ...
            }
        }
    }
}
}
4

1 回答 1

0

首先,LiveData除非您的用例严格要求,否则不要使用。

在你的里面ViewModel,你可以像这样创建一个列表,

class MVVM : ViewModel(){
 var itemsList = mutableStateListOf<Item>()
}

然后,在您的活动中,您可能不应该传递整个视图模型,但这完全取决于您。所以,在这种情况下

@Composable
fun LayoutsCodelab(viewModel: MyViewModel) {
val list = viewModel.itemsList

Scaffold {
    LazyColumn(state = rememberLazyListState()) {
        items(list.size) {
            val item = list[it]

            // Don't use mutableStateOf willy-nilly,
            /*val itemBackgroundColor by mutableStateOf(
                if (item.judge) Color.Blue else Color.Gray)*/
            
            Row(modifier = Modifier.background(color = if(item.judge) ColorBlue else Color.Gray)) {
                //other detail codes ...
            }
        }
    }
}

您不需要mutableStateOf在原始代码中调用它的地方使用 's 。考虑参加State-in-Compose代码实验室以进一步了解。

另外,如果项目是根据更新的列表呈现的,我认为即使没有这些修改,您的代码实际上也应该可以正常工作,但问题(我大约 2/3 肯定)可能在于“其他代码细节...... " 部分,其中存在的 Composables 可能占据了 的整个空间item,因此隐藏了修改后的背景。考虑将这个背景修饰符也应用到那里的子 Composables 上,然后检查它是否有效。

于 2022-02-27T19:46:16.860 回答