带有Hilt的匕首从模块中将ActivityContext注入适配器 [英] Dagger with Hilt inject ActivityContext in adapter from module

查看:649
本文介绍了带有Hilt的匕首从模块中将ActivityContext注入适配器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用的是匕首和刀柄,我想将@ActivityContext从模块注入到适配器,但出现此错误-

I'm using dagger and hilt and i want to inject @ActivityContext from a module to an Adapter but i'm getting this error -

ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1ANTLR Tool version 4.5.3 used for code generation does not match the current runtime version 4.7.1ANTLR Runtime version 4.5.3 used for parser compilation does not match the current runtime version 4.7.1/mnt/My Projects/app/build/generated/source/kapt/debug/app/myapp/MyApp_HiltComponents.java:156: error: [Dagger/MissingBinding] @dagger.hilt.android.qualifiers.ActivityContext android.content.Context cannot be provided without an @Provides-annotated method.
  public abstract static class ApplicationC implements MyApp_GeneratedInjector,
                         ^
      @dagger.hilt.android.qualifiers.ActivityContext android.content.Context is injected at
          app.myapp.di.modules.activitiesModules.HomeActivityModule.provideAdapterFragmentState(context)
      app.myapp.ui.base.AdapterFragmentState is injected at
          app.myapp.ui.home.HomeActivity.adapterFragmentState
      app.myapp.ui.home.HomeActivity is injected at

这是我的HomeActivityModule-

This is my HomeActivityModule -

@Module
@InstallIn(ActivityRetainedComponent::class)
object HomeActivityModule {

    @Provides
    @ActivityRetainedScoped
    fun provideAdapterFragmentState(@ActivityContext context: Context): AdapterFragmentState {
        return AdapterFragmentState(context)
    }

}

这是我的适配器-

@ActivityRetainedScoped
class AdapterFragmentState @Inject constructor(@ActivityContext context: Context)
    : FragmentStateAdapter(context as AppCompatActivity){

哪个部分是错误的?

推荐答案

@Module
@InstallIn(ActivityComponent::class)
object HomeActivityModule {

    @Provides
    @ActivityScoped
    fun provideAdapterFragmentState(@ActivityContext context: Context): AdapterFragmentState {
        return AdapterFragmentState(context)
    }

}

已编辑:

因为ActivityRetainedComponent存在于配置更改中,而ActivityComponent没有。

Because ActivityRetainedComponent lives across configuration changes and ActivityComponent doesn't.

如果要注入@ActivityContext,则应安装模块在ActivityComponent中,并且注入的对象必须为@ActivityScoped。

If you want to inject @ActivityContext, your module should be installed in ActivityComponent and the injected objects must be @ActivityScoped.

这篇关于带有Hilt的匕首从模块中将ActivityContext注入适配器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆