How to use Dependency Injection for Fragment or Activity creation

345 Views Asked by At

I'm writing an SDK, intended for 3rd party usage. That SDK provides a complex interactions between a series of Activity and Fragment. One of the things that we would like to be able to do is allow a user of the SDK to customize functionality by subclassing our provided Activity and/or Fragment Currently, this is handled somewhat clumsily using a factory model:

class WidgetActivity extends Activity {
    public WidgetFragment buildWidgetFragment() {
        return new WidgetFragment();
    }
}

class WidgetFragment extends Fragment {
}

class IntentFactory {
    public WidgetActivity buildWidgetIntent() {
        return new Intent(WidgetActivity.class);
    }
}

But, this means that if the user wants to customize a WidgetFragment, they have to provide subclasses of IntentFactory, WidgetActivity, and WidgetFragment. What's more, WidgetFragment is actually used between two or three different Activity's, so they have to provide subclasses of each of those as well, and there's no real protection against missing some of them. Obviously, this could be alleviated by adding in an FragmentFactory:

class FragmentFactory {
    public WidgetFragment buildWidgetFragment() {
        return new WidgetFragment();
    }
}

But, at some point, it was suggested that this might be an appropriate situation for applying IoC and DI models.

There are a lot of examples of doing DI within either an Activity or a Fragment, but so far, I haven't found any examples of using a DI model for to create the correct Activity or Fragment in the first place.

Is this possible using either RoboGuice or Dagger2?

If so, how?

Is there another alternative I'm missing?

0

There are 0 best solutions below