Dagger2: no injector factory bound for fragment

后端 未结 3 826
孤独总比滥情好
孤独总比滥情好 2021-01-04 05:44

I\'m trying to convert a project that I\'m building to use the dagger-android API for the DI framework, but I\'m running into a dead end with an IllegalArgumentException whe

3条回答
  •  挽巷
    挽巷 (楼主)
    2021-01-04 06:28

    When you inject using AndroidSupportInjection.inject(this) from your HomeFragment, Dagger will walk the parent-fragment hierarchy to find someone that implements HasSupportFragmentInjector. To make it work, make your MainActivity extends DaggerAppCompatActivity which implements HasSupportFragmentInjector.

    From the doc of AndroidSupportInjection.inject(Fragment fragment):

    Injects {@code fragment} if an associated {@link dagger.android.AndroidInjector} implementation can be found, otherwise throws an {@link IllegalArgumentException}.

    Uses the following algorithm to find the appropriate {@code AndroidInjector} to use to inject {@code fragment}:

    1. Walks the parent-fragment hierarchy to find the a fragment that implements {@link HasSupportFragmentInjector}, and if none do
    2. Uses the {@code fragment}'s {@link Fragment#getActivity() activity} if it implements {@link HasSupportFragmentInjector}, and if not
    3. Uses the {@link android.app.Application} if it implements {@link HasSupportFragmentInjector}.

    If none of them implement {@link HasSupportFragmentInjector}, a {@link IllegalArgumentException} is thrown.

    @throws IllegalArgumentException if no parent fragment, activity, or application implements {@link HasSupportFragmentInjector}.

    With this, Dagger will use

    @FragmentScope
    @ContributesAndroidInjector
    abstract HomeFragment provideHomeFragment();
    

    from your MainActivityModule to inject inside your HomeFragment.

提交回复
热议问题