尝试在动态功能模块中创建 ViewModel private val viewModel: PostDetailViewModel by viewModels()
在片段中
class PostDetailFragment : DynamicNavigationFragment<FragmentPostDetailBinding>() {
private val viewModel: PostDetailViewModel by viewModels()
override fun getLayoutRes(): Int = R.layout.fragment_post_detail
override fun bindViews() {
// Get Post from navigation component arguments
val post = arguments?.get("post") as Post
dataBinding.item = post
viewModel.updatePostStatus(post)
}
override fun onCreate(savedInstanceState: Bundle?) {
initCoreDependentInjection()
super.onCreate(savedInstanceState)
}
private fun initCoreDependentInjection() {
val coreModuleDependencies = EntryPointAccessors.fromApplication(
requireActivity().applicationContext,
DomainModuleDependencies::class.java
)
DaggerPostDetailComponent.factory().create(
coreModuleDependencies,
requireActivity().application
)
.inject(this)
}
}
结果错误
Caused by: java.lang.InstantiationException: java.lang.Class<com.x.post_detail.PostDetailViewModel> has no zero argument constructor
它适用于应用程序模块中的任何片段,但不适用于动态功能模块。将 ViewModel 添加到动态功能模块的正确方法是什么?我应该使用 ViewModelFactory 在 app 模块中创建 ViewModel 并从 app 模块中获取它们吗?