How to inject a fragment from the package androidx.fragment.app.Fragment ?
I'm using the dagger-android framework to inject my dependencies in my code.
As the documentation says I do this to inject my fragment
@Override public void onAttach(Activity activity) { AndroidInjection.inject(this); super.onAttach(activity); // ... }
the problem is that AndroidSupportInjection class accept only fragments of the package android.support.v4.app.Fragment or if I use AndroidInjection class only accept fragments of the package android.app.Fragment and I want to use fragments of the androidx.fragment.app.Fragment package.
Also DaggerFrament extend from android.support.v4.app.Fragment and want to use a fragment from androidx
And If I try to implement HasSupportFragmentInjector also this interface use a fragment from android.support
Dagger generates code similar to what you would have written manually. Internally, Dagger creates a graph of objects that it can reference to find the way to provide an instance of a class. For every class in the graph, Dagger generates a factory-type class that it uses internally to get instances of that type.
Dagger 2 is a compile-time android dependency injection framework that uses Java Specification Request 330 and Annotations. Some of the basic annotations that are used in dagger 2 are: @Module This annotation is used over the class which is used to construct objects and provide the dependencies.
Dagger cannot instantiate or inject classes that do not have neither @Inject nor @Provides annotations.
add the below code to your gradle.properties
android.useAndroidX=true
android.enableJetifier=true
And if you are trying to inject into a Fragment you have to replace AndroidInjection.inject(this)
with AndroidSupportInjection.inject(this)
I had the same problem in case of HasFragmentInjector. You need to use HasSupportFragmentInjector for fragment injection. This is because, HasFragmentInjector
uses android.app.Fragment
which is not effected by jetifier
. You need to add android-dagger-support
library, jetifier
converts all the support packages to androidx in Studio 3.3 (if jetifier
is enabled).
If jetifier does not change support packages to androidx packages. You can download jetifier
tool from here and convert the android-dagger-support.aar file manually by using the following command.
./jetifier-standalone -i dagger-android-support-<version>.aar -o <output-name>
Then add the library to your project. This is the HasSupportFragment class after conversion
import androidx.fragment.app.Fragment; import dagger.android.AndroidInjector; public interface HasSupportFragmentInjector { AndroidInjector<Fragment> supportFragmentInjector(); }
Somehow, jetifier tool was not converting libraries in AndroidStudio. I had to do it manually.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With