Interfacing Between Fragments and Activities in Android

Use the getActivity method within any Fragment to return a reference to the Activity within which it’s embedded. This is particularly useful for fi nding the current Context, accessing other Fragments using the Fragment Manager, and finding Views within the Activity’s View hierarchy.

TextView textView = (TextView)getActivity().findViewById(R.id.textview);

Although it’s possible for Fragments to communicate directly using the host Activity’s Fragment Manager, it’s generally considered better practice to use the Activity as an intermediary. This allows the Fragments to be as independent and loosely coupled as possible, with the responsibility for deciding how an event in one Fragment should affect the overall UI falling to the host Activity

Where your Fragment needs to share events with its host Activity (such as signaling UI selections), it’s good practice to create a callback interface within the Fragment that a host Activity must implement.

Defining Fragment event callback interfaces

public interface OnSeasonSelectedListener {
 public void onSeasonSelected(Season season);
}
 
private OnSeasonSelectedListener onSeasonSelectedListener;
private Season currentSeason;
@Override
public void onAttach(Activity activity) {
 super.onAttach(activity);
 
 try {
 onSeasonSelectedListener = (OnSeasonSelectedListener)activity;
 } catch (ClassCastException e) {
 throw new ClassCastException(activity.toString() + 
 “ must implement OnSeasonSelectedListener”);
 }
}
private void setSeason(Season season) {
 currentSeason = season;
 onSeasonSelectedListener.onSeasonSelected(season);
}

Leave a Comment