android - Dagger 2.11 注入(inject)不适用于 fragment

标签 android android-fragments dependency-injection dagger-2

您好,我正在尝试将依赖项注入(inject)到我的 Android Fragment 类中,就像我为 Activity 所做的那样,它似乎没有将对象注入(inject)到 fragment 中的变量中。

这是我的绑定(bind)模块

@Module
abstract class HomeAndroidBinding{

    /**
     * Activity bindings here
     */
    @ContributesAndroidInjector(modules = [MyModule ::class])
    @MyScope
    abstract fun bindHomeActivity() : HomeActivity

    /**
     * Fragment Bindings here
     */
    @ContributesAndroidInjector(modules = [MyModule ::class])
    @MyScope
    abstract fun bindHomeFragment() : HomeFragment
}

这是我的 Fragment 类

class HomeFragment : Fragment() {

   @Inject
    lateinit var productStorage: ProductStorageContract //error, not inialised

    ...

    override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {
        productStorage.getData()
    }

这是我的 ApplicationComponent,它加载并绑定(bind)所有内容

    @Singleton
@Component(modules = arrayOf(MyMainModule::class,
        AndroidSupportInjectionModule::class,
        HomeAndroidBinding::class,
        ))
interface ApplicationComponent : AndroidInjector<DaggerApplication> {
    fun inject(myApplication: MyApplication)
    override fun inject(instance: DaggerApplication)

    @Component.Builder
    interface Builder {
        @BindsInstance
        fun application(applicaton: MyApplication): Builder

        fun build(): ApplicationComponent
    }


}

相同的productStorage变量在HomeActivity上运行良好

最佳答案

您还需要在 fragment 中包含以下内容:

override fun onAttach(context: Context) {
    AndroidSupportInjection.inject(this)
    super.onAttach(context)
}

完整示例:https://github.com/joreilly/galway-bus-android/blob/master/app/src/main/java/com/surrus/galwaybus/ui/RoutesFragment.kt

关于android - Dagger 2.11 注入(inject)不适用于 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407092/

相关文章:

android - onFailure 方法中的 OkHttp 响应状态码

Android:ADB 更新 Google Play 服务 'Failure'

android - 从另一个进程中的应用程序上下文启动 Activity

java - 是否有必要在分离时将 Fragment 接口(interface)监听器设置为 null?

c# - Autofac 在深层解析

android - 很难找到发布到 Google Play 商店的应用

带有 ActionbarSherlock 的 Android TabsAdapter

android - 如何在 fragment 中实现 onBackPressed() 和 Intent ?

c# - 无论存在与否,AutoFac 创建类型

android - 替换正在运行的 roboguice 应用程序中的单例实例