viewModel 的可变值状态不起作用

Shi*_*a s 4 android kotlin android-jetpack-compose compose-recomposition

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

当状态位于组合内部时,一切工作正常

var mSelectedText by remember { mutableStateOf("") }
Run Code Online (Sandbox Code Playgroud)

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

 private val _mainCatTitle = mutableStateOf("")
 val mainCatTitle: State<String> = _mainCatTitle
Run Code Online (Sandbox Code Playgroud)

我的可组合项

   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 " )
}
Run Code Online (Sandbox Code Playgroud)

在 DropDownMenuItem 内的第一个日志中,日志显示“选定”字段,但第二个日志为空

已附上图片 在此输入图像描述

z.g*_*g.y 5

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

  DropdownMenuItem(onClick = {
        mainCatTitle = it.category_name.toString()
        ...
Run Code Online (Sandbox Code Playgroud)

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

DropdownMenuItem(onClick = {
       viewModel.onSelectedItem(it) // <-- this function
       ...
}
Run Code Online (Sandbox Code Playgroud)

并在你的ViewModel更新状态是这样的

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