我的片段活动中有两个片段类(#1和#2)。片段活动用于视图寻呼机。 如何在片段#1中调用片段#2的方法? 请注意附图。
答案 0 :(得分:1)
首选方法是让Fragments之间的所有通信都通过其公共父Activity:
public class MyActivity implements WantsACalledListener {
private Fragment fragment2;
@Override
public onWantsACalled() {
fragment2.a();
}
}
并且,根据Android文档:http://developer.android.com/guide/components/fragments.html
public static class Fragment1 {
WantsACalledListener mListener;
...
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
mListener = (WantsACalledListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement WantsACalledListener");
}
}
...
private void someMethod() {
mListener.onWantsACalled();
}
}
因此,Activity可以轻松地保留对其所有子片段的引用,并且子片段在其onAttach方法中获得对其父Activity的引用。