Inter-Fragment communications – interfaces revisited
The main point of Fragments is that they have flexibility and reusability. If you remember, back in Chapter 12, Having a Dialogue with the User, when we were passing Note
to and from a Fragment
dialog, we added a method to Fragment
and then called this method from the instance of the dialog in order to pass in the correct note that is to be shown. And when we added a new note in a dialog, we used getActivity()
to get a reference to MainActivity
in order to return the new note to be added to ArrayList
of notes. Here is the code as a reminder:
// Get a reference to MainActivity MainActivity callingActivity = (MainActivity) getActivity(); // Pass newNote back to MainActivity callingActivity.createNewNote(newNote);
The problem with this is that it assumes that the communication is with an Activity
called MainActivity
.
Although this works in the Note To Self scenario, it is inflexible because this means that our fragments can only be...