I want to introduce dependency injection through Dagger to a project. The following code acts as an example to describe the problem of injection into static classes.
The static method setupTextView()
is called from multiple classes:
public abstract class TextViewHelper {
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) {
MyApp.getTracker().track(trackingPoint);
}
});
}
}
Here is one example how the helper method is used:
TextViewHelper.setupTextView(this, R.id.some_text_view,
R.string.some_text,
TrackingPoint.SomeTextClick);
The tracking used in the helper method is provided by the application class:
public class MyApp extends Application {
private static Tracking mTracking;
public void onCreate() {
super.onCreate();
mTracking = getTracking(getApplicationContext());
}
private Tracking getTracking(Context context) {
if (BuildConfig.DEBUG) {
return new NoTracking();
} else {
return new NsaTracking(context);
}
}
public static Tracking getTracker() {
return mTracking;
}
}
Now, I want to inject the tracking via Dagger. When I refactored the code I noticed that I would need to pass the tracking object from my Activity or Fragment to the static helper since I cannot directly inject into the static class:
TextViewHelper.setupTextView(this, R.id.some_text_view,
R.string.some_text,
TrackingPoint.SomeTextClick,
Tracking tracking);
This does not feel like a good design pattern - since I pass the TrackPoint
and the Tracking
object. How would you improve this?