【问题标题】:How to inject DialogFragment with Dagger?如何用 Dagger 注入 DialogFragment?
【发布时间】:2020-03-17 00:51:02
【问题描述】:

请我在 DI 中使用 dagger 2,如何将对话框片段注入到我的活动中,以及如何使用 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)
   }
}

然后我创建我的 DialogFragment 模块

  @Module
 class DialogFragmentsModule {

  @Singleton
  @Provides
  fun myDialogFragment() = MainAlertDialogFragment()

 }

我创建了这个注释

          @MustBeDocumented
@Target(
    AnnotationTarget.FUNCTION,
    AnnotationTarget.PROPERTY_GETTER,
    AnnotationTarget.PROPERTY_SETTER
)
@Retention(AnnotationRetention.RUNTIME)
@MapKey
annotation class DialogFragmentKey(val value: KClass<out DialogFragment>)

我注入 AndroidInjectionModule 和 AndroidSupportInjectionModule , ApplicationComponent ,DialogFragmentsModule

这是我的对话框片段标题

 class MainAlertDialogFragment @Inject constructor() : 
 DaggerDialogFragment(), HasAndroidInjector {

我想像那样注射它

      @Inject
lateinit var dialog: MainAlertDialogFragment

【问题讨论】:

  • 您好,您好像在 StackOverflow 上已经有一段时间了,您应该知道您必须添加额外的细节,例如代码 sn-p 以及您尝试过什么,以便这里的社区可以提供帮助你相应地。
  • 抱歉我赶时间

标签: android dagger-2


【解决方案1】:

您需要将此代码添加到 MainAlertDialogFragment

  @Override
  public void onAttach(Context context) {
    AndroidSupportInjection.inject(this);
    super.onAttach(context);
  }

或者只是从 DaggerDialogFragment 扩展它

... 并编辑您的模块。添加这个代替提供功能

@Singleton
@ContributesAndroidInjector(
    modules = [
           //
    ]
)
fun contributeMainAlertDialogFragment(): MainAlertDialogFragment

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2014-08-30
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多