1

please i am using dagger 2 for the DI , how to inject dialog fragment into my activity , and how to use the DaggerDialogFragment class provided by dagger

i create my 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)
   }
}

and then i create my DialogFragment Module

  @Module
 class DialogFragmentsModule {

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

 }

i create this annontation

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

i inject AndroidInjectionModule and AndroidSupportInjectionModule , ApplicationComponent ,DialogFragmentsModule

this is my dialog fragment header

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

and i wanna inject it like that

      @Inject
lateinit var dialog: MainAlertDialogFragment
B.mansouri
  • 376
  • 7
  • 16
  • Hello, seems like you've been on StackOverflow for quite some time, you should know that you must add extra details such as code snippet and what have you tried, so that community here can help you accordingly. – Parag Pawar Nov 21 '19 at 07:05
  • sorry i was in a hurry – B.mansouri Nov 21 '19 at 07:17

1 Answers1

5

you need add this code to MainAlertDialogFragment

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

or just extend it from DaggerDialogFragment

... and edit you module. Add this instead provide function

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