你说的不对,我需要的是androidx.lifecycle.viewmodel类中的MutableCreationExtras 使用方法,
时间: 2023-05-30 19:03:39 浏览: 131
对不起,我理解错了您的问题。下面是使用MutableCreationExtras的示例代码:
1. 在ViewModel类中声明MutableCreationExtras对象:
```kotlin
class MyViewModel(private val savedStateHandle: SavedStateHandle) : ViewModel() {
val extras = MutableCreationExtras()
// ...
}
```
2. 在Activity或Fragment中使用MutableCreationExtras对象:
```kotlin
class MyActivity : AppCompatActivity() {
private val viewModel: MyViewModel by viewModels()
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_my)
// 从ViewModel中获取MutableCreationExtras对象
val extras = viewModel.extras
// 设置值
extras["key1"] = "value1"
extras["key2"] = 123
// 获取值
val value1 = extras["key1"] as String
val value2 = extras["key2"] as Int
}
}
```
注意:MutableCreationExtras对象只能在ViewModel的构造函数中声明和初始化,否则会导致运行时错误。并且MutableCreationExtras对象只能在ViewModel创建后使用,否则会返回null。
阅读全文