[英]Dagger 2.11 injection not working for fragments
嗨,我正尝试以与我进行活动相同的方式向我的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变量在HomeActivity上正常工作
您还需要在片段中包括以下内容:
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
感谢@Jeff Browman。
问题是我的片段没有使用DaggerFragment超类
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.