How to inject into static classes using Dagger? How to inject into static classes using Dagger? android android

How to inject into static classes using Dagger?


In your TextViewHelper create a static field with the tracker.

public class TextViewHelper {    private TextViewHelper(){}    @Inject    static Tracking sTracker;    public static void setupTextView(TextView textView,                                      Spanned text,                                      TrackingPoint trackingPoint) {        textView.setText(text, TextView.BufferType.SPANNABLE);        textView.setMovementMethod(LinkMovementMethod.getInstance());        textView.setOnClickListener(new View.OnClickListener() {            @Override            public void onClick(View v) {                sTracker.track(trackingPoint);            }        });    }}

Here is how to configure the module:

@Module(staticInjections = TextViewHelper.class)public class TrackerModule {...}

And the most important, call injectStatics on your graph.

mObjectGraph = ObjectGraph.create(new TrackerModule());mObjectGraph.injectStatics();

Edit:

As you noted Dagger's documentation states that static injections "should be used sparingly because static dependencies are difficult to test and reuse." It is all true, but because you asked how to inject object into utility class this is the best solution.

But if you want your code to be more testable, create a module like below:

@Module(injects = {classes that utilizes TextViewHelper})public class TrackerModule {      @Provides      Tracking provideTracker() {           ...      }      @Provides      @Singleton      TextViewHelper provideTextViewHelper(Tracking tracker) {           return new TextViewHelper(tracker);      }}

Now you can remove static from TextViewHelper methods because this utility class will be injected using dagger.

public class TextViewHelper {    private final Tracking mTracker;    public TextViewHelper(Tracking tracker){        mTracker = tracker;    }    public void setupTextView(TextView textView,                               Spanned text,                               TrackingPoint trackingPoint) {         ...    }}

This is how it should be done if you want to follow good practices. Both solution will work so it's up to you to choose one.