Dagger Hilt - 如何将 ViewModel 注入适配器?

Dagger Hilt - How do I inject the ViewModel into the Adapter?

我正在尝试将 ViewModel 注入适配器。注入 Fragment 时工作正常。

ViewModel:

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;

Selam Murat,如果您想使用 viewModels() 委托创建 ViewModel,则必须添加 Kotlin 片段依赖项。

implementation 'androidx.activity:activity-ktx:1.1.0'
implementation 'androidx.fragment:fragment-ktx:1.1.0'

还在你的 build.gradle(Module: app) 文件下面的 buildTypes

中添加这个编译选项
compileOptions {
    sourceCompatibility JavaVersion.VERSION_1_8
    targetCompatibility JavaVersion.VERSION_1_8
    kotlinOptions {
        jvmTarget = "1.8"
    }
}

除此之外不要在空构造函数前使用@Inject 或@ViewModelInject 注解。

这是给你的更新: 也许您在尝试构造函数注入时忘记添加@Provides 注释。

通常,您不应将 ViewModel 注入 Adapter,因为 Adapter 是 presentation 层的一部分,是 Android-specific 的东西。 ViewModel 通常独立于 Android,尽管 AAC 的 ViewModel 与其相关联。

您应该在 ViewModel 中获取数据并通过 LiveData 将其传递给 Fragment,然后从 Fragment 中填充适配器。

by viewModels() 没有在 Adapter 中定义,因为它是 Fragment 的扩展函数,只能在 Fragment 中使用。因此,将您的 ViewModel 从 Adapter 移回 Fragment。这也将修复您的编译错误,因为 Hilt 不会注入适配器。