as the title says, I'm trying to figure out which one is the best way to inject a dependency in a Fragment. I want to be independent from external frameworks like RoboGuice etc.
Now, in the simplest way possible, I have an interface that abstracts some kind of logic, and, from an Activity, I want to inject an implementation of this interface. I know that I have to provide a default constructor for my fragment, since the system might need to recreate the fragment at some point, and that the usual way to create a new instance of the fragment is to provide static method that handles the creation like this:
public static Fragment newInstance() {
final Bundle bundle = new Bundle();
...
final Fragment fragment = new MyFragment();
fragment.setArguments(bundle);
return fragment;
}
How can I pass my dependency to the fragment? Should I make it implement the Parcelable or Serializable interfaces and then pack it in the Bundle? Is there some other way to achieve the result?
A simple solution is to declare an interface which is declaring the Dependencies required for the Fragment. Then let the Context of the Fragment implement this interface, and poll the dependencies when needed from the Context.
Contract:
public interface MyDependencies {
MyDep getDep();
}
Activity:
public MyActivity extends Activity implements MyDependencies {
@Override
public MyDep getDep(){
return createMyDependencyOrGetItFromASingletonOrGetItFromApplication()
}
}
Fragment:
public void onActivityCreated(Bundle b){
super.onActivityCreated(b)
if (getActivity() instanceOf MyDependencies) {
MyDep dep = ((MyDependencies) getActivity).getDep();
} else {
throw new RuntimeException("Context does not support the Fragment, implement MyDependencies")
}
}
So, in fact, there is no unnecessary coupling to the Activity because the contract is defined by an interface.
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