Communicating with Other Fragments

To allow a Fragment to communicate up to its Activity, you can define an interface in the Fragment class and implement it within the Activity. The Fragment captures the interface implementation during its onAttach() 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:

publicclassHeadlinesFragmentextendsListFragment{
OnHeadlineSelectedListener mCallback;

// Container Activity must implement this interface
publicinterfaceOnHeadlineSelectedListener{
publicvoid onArticleSelected(int position);
}

@Override
publicvoid 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){
thrownewClassCastException(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
publicvoid 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.

publicstaticclassMainActivityextendsActivity
implementsHeadlinesFragment.OnHeadlineSelectedListener{
...

publicvoid onArticleSelected(int position){
// The user selected the headline of an article from the HeadlinesFragment
// Do something here to display that article
}
}


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章