The cleanest way is to define an interface that the Activity
that contains the Fragment
s will implement. This is how I recently solved this:
First define the interface in it's own file, because it has to 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
s you can get the hosting Activity
with getActivity()
and to use the communication methods just cast the activity into the implemented communication interface like so:
((FragmentCommunication) getActivity()).printMessage("Hello from Fragment!");
EDIT: To further pass the message to other Fragment
s do this: since your tabs all extend Fragment
it is the best to create another interface
public Interface ReceiverInterface
{
public void receiveMessage(String str);
}
Then implement this in your tabs
public class Tab1 extends Fragment implements ReceiverInterface
{
// .... code .....
public void receiveString(String str)
{
//use str
}
}
To further send this message to other Fragments it is required that the activity sees them. For example now modify the printMessage()
that Activity
implements to this
public void printMessage(String message)
{
System.out.println(message);
//Send the message that came from one fragment to another
if (tabFragment1 instanceof ReceiverInterface){
((ReceiverInterface) tabFragment1).receiveMessage(message);
}
}
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…