Mur*_*KSU 0 android viewmodel kotlin dagger dagger-hilt
我正在尝试将 ViewModel 注入适配器中。注入 Fragment 时效果很好。
\n视图模型:
\nclass HomeViewModel @ViewModelInject constructor(\n): ViewModel() \nRun Code Online (Sandbox Code Playgroud)\n分段:
\n@AndroidEntryPoint\nclass HomeFragment : BaseFragment<FragmentHomeBinding, HomeViewModel>(\nR.layout.fragment_home\n) {\n\nprivate val viewModel: HomeViewModel by viewModels()\nRun Code Online (Sandbox Code Playgroud)\n目前为止没有问题。但是当我尝试注入适配器时出现问题。
\nclass HomeListAdapter @Inject constructor(\n): BaseListAdapter<Users>(\nitemsSame = { old, new -> old.username == new.username },\ncontentsSame = { old, new -> old == new }\n) {\n\n\n\nprivate val viewModel: HomeViewModel by viewModels() //viewModels() unresolved reference\nRun Code Online (Sandbox Code Playgroud)\n\n更新:
\n如果我尝试使用构造函数注入或字段注入,我会收到以下错误:
\n error: [Dagger/MissingBinding] ***.home.HomeViewModel cannot be provided without an @Inject constructor or an @Provides-annotated method.\n public abstract static class ApplicationC implements App_GeneratedInjector,\n ^\n ***.home.HomeViewModel is injected at\n ***.home.adapter.HomeListAdapter.viewModel\n ***.home.adapter.HomeListAdapter is injected at\n ***.home.HomeFragment.viewAdapter\n ***.home.HomeFragment is injected at\n ***.home.HomeFragment_GeneratedInjector.injectHomeFragment(***.home.HomeFragment) [***.App_HiltComponents.ApplicationC \xe2\x86\x92 ***.App_HiltComponents.ActivityRetainedC \xe2\x86\x92 ***.App_HiltComponents.ActivityC \xe2\x86\x92 ***.App_HiltComponents.FragmentC]\nRun Code Online (Sandbox Code Playgroud)\n适配器:
\nclass HomeListAdapter @Inject constructor(\n): BaseListAdapter<Users>(\nitemsSame = { old, new -> old.username == new.username },\ncontentsSame = { old, new -> old == new }\n) {\n\n\n@Inject lateinit var viewModel: HomeViewModel;\nRun Code Online (Sandbox Code Playgroud)\n
一般来说,你不应该将ViewModel注入到Adapter中,因为Adapter是表示层的一部分,是Android特有的东西。一般来说,ViewModel 是独立于 Android 的,尽管 AAC 的 ViewModel 与之相关。
您应该在 ViewModel 中获取数据并通过 LiveData 将其传递给 Fragment,然后从 Fragment 中填充您的适配器。
by viewModels()没有在 Adapter 中定义,因为它是 Fragment 的扩展函数,只能在 Fragment 中使用。因此,将 ViewModel 从 Adapter 移回 Fragment。这也将修复您的编译错误,因为 Hilt 不会注入适配器。
| 归档时间: |
|
| 查看次数: |
3086 次 |
| 最近记录: |