gpt4 book ai didi

android - viewModel 的可变值状态不起作用

转载 作者:行者123 更新时间:2023-12-05 01:49:12 28 4
gpt4 key购买 nike

我的 ViewModel 中有一个 mutablestate,我试图在我的可组合项中设置和访问它。当我使用 remember 的委托(delegate)属性时,它正在工作,但是在 viewModel 中创建它并在 compose 中访问它之后,变量的状态为空如何使用 viewModel 的状态

当状态在 compose 内时一切正常

var mSelectedText by remember { mutableStateOf("") }

但是当我从 viewModel 更改中使用它并设置我的 OutlinedTextField 值 = mainCatTitle 和 onValueChange = {mainCatTitle = it} 时,所选标题未显示在 OutlinedTextField 中为空

 private val _mainCatTitle = mutableStateOf("")
val mainCatTitle: State<String> = _mainCatTitle

我的可组合项

   var mSelectedText by remember { mutableStateOf("") }
var mainCatTitle = viewModel.mainCatTitle.value

Column(Modifier.padding(20.dp)) {

OutlinedTextField(
value = mainCatTitle,
onValueChange = { mainCatTitle = it },
modifier = Modifier
.fillMaxWidth()
.onGloballyPositioned { coordinates ->
mTextFieldSize = coordinates.size.toSize()
},
readOnly = true,
label = { Text(text = "Select MainCategory") },
trailingIcon = {
Icon(icon, "contentDescription",
Modifier.clickable { mExpanded = !mExpanded })
}
)

DropdownMenu(expanded = mExpanded,
onDismissRequest = { mExpanded = false },
modifier = Modifier.width(with(
LocalDensity.current) {
mTextFieldSize.width.toDp()
})) {
selectCategory.forEach {
DropdownMenuItem(onClick = {
mainCatTitle = it.category_name.toString()
mSelectedCategoryId = it.category_id.toString()
mExpanded = false
Log.i(TAG,"Before the CategoryName: $mainCatTitle " )
}) {

Text(text = it.category_name.toString())
}
}
}
}

Log.i(TAG,"Getting the CategoryName: $mainCatTitle " )
}

在我的第一个日志中的 DropDownMenuItem 中,日志显示了 Selected 字段,但第二个日志是空的

附上图片 enter image description here

最佳答案

您直接从 onClick 修改 mainCatTitle 变量,而不是您的 ViewMoel 提升的状态

  DropdownMenuItem(onClick = {
mainCatTitle = it.category_name.toString()
...

并且因为您没有提供有关您的 ViewModel 的任何信息,我假设并建议您创建一个函数,如果您的 ViewModel 中没有您可以这样调用,

DropdownMenuItem(onClick = {
viewModel.onSelectedItem(it) // <-- this function
...
}

在你的 ViewModel 中,你像这样更新状态

fun onSelectedItem(item: String) { // <-- this is the function
_mainCatTitle.value = item
}

关于android - viewModel 的可变值状态不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74388432/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com