我仍然试图掌握依赖注射的Dagger心态,并遇到了一些麻烦。我有一个MyNavBar,它是一个片段中的View。我无法弄清楚如何将我的应用程序的MainWrapper类注入其中。以下是我的代码的布局方式:
我的应用Android模块中有一个MainActivity:
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);
}
然后,MainWrapper存在于库中,其中包含几乎所有应用程序的代码:
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是一个非常标准的片段:
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;
}
}
最后,这里是MyNavBar片段:
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.
}
});
}
}
如何让MainWrapper使用DI将包装器注入MyNavBar类?我意识到我可以将MainWrapper注入MainFragment,然后在MyNavBar上创建一个setter,但这似乎首先打败了DI的目的。
我想最终我要问的是:如果你有主要的Activity,它创建了一个片段,并且该片段有视图,你怎么能在保持ObjectGraph的同时注入这些片段的视图只在主要活动中?在某些时候,你不必在片段的视图上调用objectGraph.inject()吗?