如果MyFragment 依赖于MyNestedFragment,并且MyNestedFragment 依赖于Deps;因此MyFragment 也依赖于Deps。当然,在调用Activity.onAttachFragment() 时不存在MyNestedFragment 的实例,因此您必须等到在MyFragment.onCreateView() 中扩展布局后,才能提供MyNestedFragment 及其依赖项。
public class MyActivity {
...
void onAttachFragment(Fragment f){
((MyFragment)f).dependencies(deps);
}
public static class MyFragment extends Fragment {
private Deps deps;
void dependencies(Deps deps) {
this.deps = deps;
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
// <fragment> element in fragment_main layout has
// android:tag set to nested_fragment
((MyNestedFragment)getChildFragmentManager()
.findFragmentByTag("nested_fragment"))
.dependencies(this.deps);
return rootView;
}
}
public static class MyNestedFragment extends Fragment {
void dependencies(Deps deps) {
...
}
}
...
}
如果所有这些看起来有点混乱,那是因为 Fragment 不是 POJO,您可以以任意方式连接起来。它们的生命周期必须由嵌套的 FragmentManager 管理。如果您以编程方式而不是使用 元素来创建片段,您将对它们的生命周期进行更多控制,但代价是更复杂。
如果您想将 Android 视为 IoC 容器,那么RoboGuice 可能就是您要找的:
public class MyActivity extends roboguice.activity.RoboFragmentActivity {
...
@Override
protected void onCreate(Bundle savedInstanceState) {
// This only needs to be called once for the whole app, so it could
// be in the onCreate() method of a custom Application subclass
RoboGuice.setUseAnnotationDatabases(false);
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
}
public static class MyNestedFragment extends Fragment {
@Inject
private Deps deps;
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// this isn't necessary if you extend RoboFragment
roboguice.RoboGuice.getInjector(activity).injectMembers(this);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
//This would not even be possible in the previous example
// because onCreateView() is called before dependencies()
// can be called.
deps.method();
View rootView = inflater.inflate(R.layout.fragment_nested, container, false);
return rootView;
}
}
}
@Singleton
public class Deps {
public void method() {
System.out.println("Deps.method()");
}
}