I'm still trying to grasp the Dagger mindset of Dependency Injection, and am running into some trouble. I have a MyNavBar which is a View in a fragment. I can't figure out how to inject my app's MainWrapper class into it. Here's how my code is laid out:
I have a MainActivity in my app's Android module:
public class MainActivity extends Activity {
private MainWrapper mainWrapper;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//Create the basic interface which will have parts swapped out with
// fragments in MainWrapper:
this.setContentView(R.layout.main);
ObjectGraph graph = ObjectGraph.create(new MyDaggerModule(this));
this.mainWrapper = new MainWrapper(graph);
}
Then, MainWrapper exists in the library which contains almost all of my app's code:
public class MainWrapper {
@Inject
protected MenuFragment menu;
@Inject
protected Activity activity;
private ObjectGraph objGraph;
public MainWrapper(ObjectGraph objGraph) {
this.objGraph = objGraph;
this.objGraph.inject(this); //populated this.menu and this.activity
Fragment mainFragment = new MainFragment();
this.objGraph.inject(mainFragment);
//Transaction to swap out blank fragment for mainFragment
// ...
}
}
MainFragment is a pretty standard fragment:
public class MainFragment extends Fragment {
protected MyNavBar navBar; //LinearLayout
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View mainContentView = inflater.inflate(R.layout.main_content, container, false);
this.navBar = (MyNavBar) mainContentView.findViewById(R.id.main_nav_bar);
return mainContentView;
}
}
Lastly, here's the MyNavBar fragment:
public class MyNavBar extends UILinearLayout {
@Inject
protected MainWrapper wrapper;
protected View menuButton;
//Constructors that call init() at the end
// ...
protected void init() {
this.setContentView(R.layout.navbar);
this.menuButton = this.findViewById(R.id.menuBtn);
this.menuButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//I want to call methods on MainWrapper here.
}
});
}
}
How can I get MainWrapper to inject wrapper into that MyNavBar class using DI? I realize I could inject MainWrapper into MainFragment, then create a setter on MyNavBar, but that seems to defeat the purpose of DI in the first place.
I guess ultimately what I'm asking is this: If you have your main Activity, which creates a fragment, and that fragment has views, how can you inject into those fragment's views while keeping the ObjectGraph only in the main activity? At some point, won't you have to call objectGraph.inject() on the fragment's Views?