Communicating with Other Fragments
Often you will want one Fragment to communicate with another, for example to change the content based on a user event.All Fragment-to-Fragment communication is done through the associated Activity.Two Fragments should never communicate directly.
Define an Interface
To allow a Fragment to communicate up to its Activity, you candefine an interface in the Fragment class and implement it within the Activity. The Fragmentcaptures the interface implementation during itsonAttach() lifecycle method and can then call the Interface methods in order to communicate with the Activity.
Here is an example of Fragment to Activity communication:
public class HeadlinesFragment extends ListFragment { OnHeadlineSelectedListener mCallback;
// 在这里定义一个接口OnHeadlineSelectedListener、一个接口方法onArticleSelected // 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"); } } ... }
Now the fragment can deliver messages to the activity by calling the onArticleSelected()
method (or other methods in the interface) using the mCallback
instance
of the OnHeadlineSelectedListener
interface.
For example, the following method in the fragment is called when the user clicks on a list item. The fragment uses the callback interface to deliver the event to the parent activity.
@Override public void onListItemClick(ListView l, View v, int position, long id) { // Send the event to the host activity mCallback.onArticleSelected(position); }
Implement the Interface
In order to receive event callbacks from the fragment, the activity that hosts it must implement the interface defined in the fragment class.
For example, the following activity implements the interface from the above example.
public static class MainActivity extends Activity implements HeadlinesFragment.OnHeadlineSelectedListener{ ... //因为MainActivity类实现了HeadlinesFragment.OnHeadlineSelectedListener接口,可以在这里重写实现onArticleSelected方法 public void onArticleSelected(int position) { // The user selected the headline of an article from the HeadlinesFragment // Do something here to display that article } }