【发布时间】:2020-10-19 13:20:56
【问题描述】:
我正在尝试将 ViewModel 注入适配器。它在注入 Fragment 时工作正常。
视图模型:
class HomeViewModel @ViewModelInject constructor(
): ViewModel()
片段:
@AndroidEntryPoint
class HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>(
R.layout.fragment_home
) {
private val viewModel: HomeViewModel by viewModels()
目前没有问题。但是当我尝试注入适配器时会出现问题。
class HomeListAdapter @Inject constructor(
): BaseListAdapter<Users>(
itemsSame = { old, new -> old.username == new.username },
contentsSame = { old, new -> old == new }
) {
private val viewModel: HomeViewModel by viewModels() //viewModels() unresolved reference
更新:
如果我尝试使用构造函数注入或字段注入,我会收到以下错误:
error: [Dagger/MissingBinding] ***.home.HomeViewModel cannot be provided without an @Inject constructor or an @Provides-annotated method.
public abstract static class ApplicationC implements App_GeneratedInjector,
^
***.home.HomeViewModel is injected at
***.home.adapter.HomeListAdapter.viewModel
***.home.adapter.HomeListAdapter is injected at
***.home.HomeFragment.viewAdapter
***.home.HomeFragment is injected at
***.home.HomeFragment_GeneratedInjector.injectHomeFragment(***.home.HomeFragment) [***.App_HiltComponents.ApplicationC → ***.App_HiltComponents.ActivityRetainedC → ***.App_HiltComponents.ActivityC → ***.App_HiltComponents.FragmentC]
适配器:
class HomeListAdapter @Inject constructor(
): BaseListAdapter<Users>(
itemsSame = { old, new -> old.username == new.username },
contentsSame = { old, new -> old == new }
) {
@Inject lateinit var viewModel: HomeViewModel;
【问题讨论】:
-
你不能这样做,因为viewModels是Fragment的扩展功能。但是,您可以通过构造函数注入或字段注入来注入视图模型。
-
你能检查我的更新吗?如果我按照你说的做,我仍然会出错。 @Diniz
-
请问您为什么要将视图模型注入适配器?也许您应该将您的工作委托给片段,片段本身将其委托给视图模型。不打算将视图模型注入适配器
标签: android kotlin viewmodel dagger dagger-hilt