How to inject into static classes using Dagger?

假如想象 提交于 2019-12-05 01:47:24

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!