[英]How to get ViewModel in Activity in Android SunFlower Project?
I am studying MVVM
of Google Android SunFlower project.我正在研究 Google Android SunFlower项目的MVVM
。
For Fragment
, it gets viewmodel
like the following对于Fragment
,它获得如下所示的viewmodel
private val plantDetailViewModel: PlantDetailViewModel by viewModels {
InjectorUtils.providePlantDetailViewModelFactory(requireActivity(), args.plantId)
}
I want to try the same method to get viewmodel
in Activity.我想尝试相同的方法在 Activity 中获取viewmodel
。 but the requireActivity()
show unresolved reference...但requireActivity()
显示未解析的引用...
And the data binding
is not working when I replace it to this
.当我将其替换为this
时, data binding
不起作用。
Does it has other pattern can be use for providePlantDetailViewModelFactory()
是否有其他模式可用于providePlantDetailViewModelFactory()
Thanks in advance.提前致谢。
You have to add these to your build.gradle你必须将这些添加到你的 build.gradle
implementation "androidx.core:core-ktx:1.3.1"
implementation "androidx.fragment:fragment-ktx:1.2.5"
Usage in Activity活动中的使用
val usersViewModel: UsersViewModel by viewModels()
Usage in Fragment在片段中的使用
// Get a reference to the ViewModel scoped to this Fragment
val viewModel by viewModels<MyViewModel>()
// Get a reference to the ViewModel scoped to its Activity
val viewModel by activityViewModels<MyViewModel>()
You need a gradle dependency on "androidx.activity:activity-ktx:$version"
.您需要对"androidx.activity:activity-ktx:$version"
的gradle 依赖。
Then you can import androidx.activity.viewModels
in your Activity.然后你可以在你的 Activity 中import androidx.activity.viewModels
。
I don't think so that you can do similar for your Activity
that's done for Fragment
. 我不认为您可以为Fragment
做类似的Activity
。
Why? 为什么?
The delegate function viewModels
is available from fragment-ktx library (Refer here for reference ) as extension for getting ViewModel
instance lazily on your value objects using by keyword. 可以从fragment-ktx库中获得委托函数viewModels
(请参阅参考资料 )作为扩展,以使用by关键字在值对象上延迟获取ViewModel
实例。
And there's no such thing available for Activities , for an instance. 例如,对于Activity来说没有可用的东西。
So, better is to create your own or find some other way like basic lazy{}
function from Kotlin standard library and providing logic to it. 因此,最好是自己创建一个或从Kotlin标准库中找到其他某种方式(例如基本lazy{}
函数)并为其提供逻辑。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.