【问题标题】:Dagger 2.11 injection not working for fragmentsDagger 2.11 注入对片段不起作用
【发布时间】:2018-01-23 16:59:24
【问题描述】:

您好,我正在尝试在我的 Android Fragment 类上注入依赖项,就像我为我的活动所做的那样,它似乎没有将对象注入到我的片段中的变量中。

这是我的绑定模块

@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
}

这是我的片段类

class HomeFragment : Fragment() {

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

    ...

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

这是我的 ApplicationComponent 加载和绑定一切

    @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 的相同 var 在 HomeActivity 上运行良好

【问题讨论】:

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


    【解决方案1】:

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

    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

    【讨论】:

    • 嗯,所以不喜欢我不需要的活动?
    • 我相信你也需要在你的活动中调用AndroidInjection.inject()(或者至少我现在正在这样做!)
    • 不,我不参加我的活动
    • hmm,不确定这将如何工作.....例如从medium.com/@iammert/…
    • @jonney 向我们展示您的活动。您可能继承自 DaggerActivity(其中包含超类中的代码),如果是,那么您可以使用 DaggerFragment 删除类似的“样板”。
    【解决方案2】:

    感谢@Jeff Browman。

    问题是我的片段没有使用 DaggerFragment 超类

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-07
      • 2018-03-09
      • 1970-01-01
      • 1970-01-01
      • 2019-01-06
      • 2018-03-31
      • 1970-01-01
      相关资源
      最近更新 更多