检查这个:Communicating with Other Fragments
定义一个接口(在片段中)
要允许 Fragment 与其 Activity 进行通信,您可以在 Fragment 类中定义一个接口并在 Activity 中实现它。 Fragment 在其 onAttach() 生命周期方法期间捕获接口实现,然后可以调用接口方法以与 Activity 通信。
以下是 Fragment 到 Activity 通信的示例:
public class HeadlinesFragment extends ListFragment {
OnHeadlineSelectedListener mCallback;
// Container Activity must implement this interface
public interface OnHeadlineSelectedListener {
public void onArticleSelected(int position);
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
// This makes sure that the container activity has implemented
// the callback interface. If not, it throws an exception
try {
mCallback = (OnHeadlineSelectedListener) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString()
+ " must implement OnHeadlineSelectedListener");
}
}
...
}
现在片段可以通过使用 OnHeadlineSelectedListener 接口的 mCallback 实例调用 onArticleSelected() 方法(或接口中的其他方法)将消息传递给 Activity。
例如,当用户单击列表项时,会调用片段中的以下方法。 Fragment 使用回调接口将事件传递给父 Activity。
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
// Send the event to the host activity
mCallback.onArticleSelected(position);
}
实现接口(在活动中)
为了从片段接收事件回调,承载它的活动必须实现片段类中定义的接口。
例如,以下活动实现了上例中的接口。
public static class MainActivity extends Activity
implements HeadlinesFragment.OnHeadlineSelectedListener{
...
public void onArticleSelected(int position) {
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article
}
}
PS1:EventBus 适合您,但如果需要,请谨慎使用,它可能会使您的代码更难阅读。
PS2:不要在 Fragment.newInstance() 中传递活动实例并使用它进行通信。活动实例可能在后台被销毁。像示例一样在 Fragment.onAttach() 中获取活动实例,框架会为您处理销毁、重新创建和重新绑定。