为什么 AdnroidInjector.inject(fragment) 使用已弃用的 android.support.v4.app.Fragment

Why AdnroidInjector.inject(fragment) uses deprecated android.support.v4.app.Fragment

我在 android 应用程序中使用 Dagger2 作为 DI,

我想通过 AndroidInjector 在片段中注入 viewModel 并有这两行:

 AndroidInjection.inject(this)
 viewModel = ViewModelProviders.of(this, viewModelFactory).get(ProductDetailViewModel::class.java)

当我的片段扩展 androidx.fragment.app.Fragment 时显示此错误:

现在我不知道我的片段应该扩展哪一个!

我在选择其中之一时收到此错误:

None of the following functions can be called with the arguments supplied: public open fun inject(activity: Activity!): Unit defined in dagger.android.AndroidInjection public open fun inject(fragment: Fragment!): Unit defined in dagger.android.AndroidInjection public open fun inject(service: Service!): Unit defined in dagger.android.AndroidInjection public open fun inject(contentProvider: ContentProvider!): Unit defined in dagger.android.AndroidInjection

androidx 是重构的库命名空间。

AndroidX is a major improvement to the original Android Support Library. Like the Support Library, AndroidX ships separately from the Android OS and provides backward-compatibility across Android releases. AndroidX fully replaces the Support Library by providing feature parity and new libraries.see here

所以我建议您首先将代码迁移到 androidx。 跟着做。

重构>迁移到 Androidx。

恭喜你,库版本不再有冲突。

我的错误是使用了 dagger-android(不是 dagger-android-support),而 dagger-android 只是:

 AndroidInjection.inject(this)

但我应该使用

 AndroidSupportInjection.inject(this)

在支持库版本的 dagger-android 中名为 dagger-android-support

Google 向我们介绍了 AndroidX,为了让所有开发人员都在同一页面上,他们弃用了 Fragment 并使支持片段成为 AndroidX.so 的一部分,您必须需要用户支持片段才能与 AnroidX 的哪个部分相同喷气背包....

https://developer.android.com/jetpack/androidx/