There are two methods that I consider viable:
A. Report on your activity and forward messages to other fragments through this activity of the owner. Details on this can be found in the official documentation for Android:
http://developer.android.com/guide/components/fragments.html#CommunicatingWithActivity
Quote:
In some cases, you may need a snippet to share events using the Event. A good way to do this is to define a callback interface inside the fragment and require that host activity execute it. When an activity receives a callback through an interface, it can share information with other fragments in the layout as needed.
The communication interface may look something like this:
public interface IActionListener{
The snippet will look something like this:
public class MyFragment extends Fragment{ private WeakReference<IActionListener> actionCallback; @Override public void onAttach(Activity activity) { super.onAttach(activity); try {
I use WeakReference here, but it really is up to you. Now you can use actionCallback to communicate with the property and call methods defined in the IActionListener.
Own activity will look like this:
public class MyActivity extends ActionBarActivity implements IActionListener { public void doSomething(){
B. Now, with regard to the second method , you can have fragments that directly communicate with each other using interfaces - this way you do not need to know the exact class of the fragment that you are talking to, which provides a free clutch.
The setup is as follows: you have two fragments (or more) and activity (to start the second fragment). We have an interface that allows Fragment 2 to send a response to fragment 1 after it is executed. For simplicity, we simply reuse interface I, defined in A.
Here is our snippet 1:
public class FragmentOne extends Fragment implements IActionListener { public void doSomething() {
Using the method described in A. Fragment 1 asks for an Activity action to start fragment 2. However, Activity will go through fragment 1 as an argument for fragment 2, so fragment 2 can later indirectly access fragment 1 and send an answer. Let's see as the prefix of Activity Fragment 2:
public class MyActivity extends ActionBarActivity {
Tip . I use-Framework Support, so if you are developing exclusively for> Android 3.0, you can simply use FragmentActivity instead of ActionBarActivity.
FragmentTwo now begins, let's see how FragmentTwo will communicate with FragmentOne:
public class FragmentTwo extends Fragment { @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { if(savedInstanceState != null){
The doSomething () implementation in fragment 1 will now be implemented.