您好,我正在尝试将依赖项注入(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)
}
关于android - Dagger 2.11 注入(inject)不适用于 fragment ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48407092/