The cleanest way is to define the interface that the Activity containing the Fragment will implement. Here is how I recently solved this:
First, define the interface in its own file, because it must be visible to other classes.
public Interface FragmentCommunication { public void printMessage(String message); .... }
In your Activity you need to implement this interface
public class MainActivity extends ActionBarActivity implements FragmentCommunication { .... public void printMessage(String message) { System.out.println(message); } }
Finally, in your Fragment you can get the hosting of the Activity using getActivity() , and to use the communication methods just enter the activity into the implemented communication interface as follows:
((FragmentCommunication) getActivity()).printMessage("Hello from Fragment!");
EDIT . To pass a message to other Fragment
public Interface ReceiverInterface { public void receiveMessage(String str); }
Then implement this on your tabs
public class Tab1 extends Fragment implements ReceiverInterface { .... code ..... public void receiveString(String str) {
To send this message to other fragments, activity is required to see them. For example, now change printMessage() , which Activity implements this
public void printMessage(String message) { System.out.println(message);
milez
source share