请问我正在使用 dagger 2 进行 DI,如何将对话框片段注入到我的活动中,以及如何使用 dagger 提供的 DaggerDialogFragment 类
我创建我的 DialogFragmentFactory
class DialogFragmentFactory @Inject constructor(
private val providers: Map<Class<out Fragment>, @JvmSuppressWildcards
Provider<DialogFragment>>
) : FragmentFactory() {
override fun instantiate(classLoader: ClassLoader, className: String):
Fragment {
// loadFragmentClass is a static method of FragmentFactory
// and will return the Class of the fragment
val fragmentClass = loadFragmentClass(classLoader, className)
// we will then be able to use fragmentClass to get the provider
// of the Fragment from the providers map
val provider = providers[fragmentClass]
if (provider != null) {
return provider.get()
}
// The provider for the fragment could be null
// if the Fragment class is not binded to the Daggers graph
// in this case, we will default to the default implementation
// which will attempt to instantiate the Fragment
// through the no-arg constructor
return super.instantiate(classLoader, className)
}
}
Run Code Online (Sandbox Code Playgroud)
然后我创建我的 DialogFragment 模块
@Module
class DialogFragmentsModule {
@Singleton
@Provides
fun myDialogFragment() = MainAlertDialogFragment()
}
Run Code Online (Sandbox Code Playgroud)
我创建这个注释
@MustBeDocumented
@Target(
AnnotationTarget.FUNCTION,
AnnotationTarget.PROPERTY_GETTER,
AnnotationTarget.PROPERTY_SETTER
)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class DialogFragmentKey(val value: KClass<out DialogFragment>)
Run Code Online (Sandbox Code Playgroud)
我注入 AndroidInjectionModule 和 AndroidSupportInjectionModule , ApplicationComponent ,DialogFragmentsModule
这是我的对话框片段标题
class MainAlertDialogFragment @Inject constructor() :
DaggerDialogFragment(), HasAndroidInjector {
Run Code Online (Sandbox Code Playgroud)
我想像那样注射
@Inject
lateinit var dialog: MainAlertDialogFragment
Run Code Online (Sandbox Code Playgroud)
您需要将此代码添加到 MainAlertDialogFragment
@Override
public void onAttach(Context context) {
AndroidSupportInjection.inject(this);
super.onAttach(context);
}
Run Code Online (Sandbox Code Playgroud)
或者只是从 DaggerDialogFragment 扩展它
...并编辑您的模块。添加这个而不是提供函数
@Singleton
@ContributesAndroidInjector(
modules = [
//
]
)
fun contributeMainAlertDialogFragment(): MainAlertDialogFragment
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
4019 次 |
| 最近记录: |