androiddagger-2preferencefragment

Using Dagger2 with PreferenceFragmentCompat


I am working on Dependency Injection in my app using Dagger2. I have a Settings screen built using PreferenceFragmentCompat. But since Dagger2 does not provide a corresponding type for PreferenceFragmentCompat (like it provides DaggerActivity to replace Activity and DaggerFragment to replace Fragment), how can I use AndroidInjection.inject(this) when injecting the dependencies inside my Settings fragment?


Solution

  • AndroidInjection.inject(fragment) requires fragment to implement dagger.android.HasAndroidInjector as can be read from the dagger.android.AndroidInjection source code.

    HasAndroidInjector can be implemented just like how DaggerFragment is implemented (source).

    public class SettingsFragment
      extends PreferenceFragmentCompat
      implements HasAndroidInjector {
    
      @Inject DispatchingAndroidInjector<Object> androidInjector;
    
      @Override
      public void onAttach(Context context) {
        AndroidSupportInjection.inject(this);
        super.onAttach(context);
      }
    
      @Override
      public AndroidInjector<Object> androidInjector() {
        return androidInjector;
      }
    
      /* Other code */
    }