Dani,
When dealing with fragments, your best means of communication between the fragments is via the activity. For example. Let us consider Activity A that has Fragments B, C, and D.
After you set the new Fragment to be placed via FragmentManager, and it is loaded, you can call the getActivity() on it to get a reference to it. A good idea is to implement an interface so that you can use it on any activity that implements it and call the callback method:
// creating the fragment here from the mainActivity
FragB fragB = new FragB();
getSupportFragmentManager().beginTransaction()
.replace(R.id.imager, fragB).commit();
// This is because my example activity implements FragBListener which is defined in the FragB class
@Override
public void onCallFromFragB() {
}
FragB
public class FragB extends Fragment {
private FragBListener activity;
....
public interface FragBListener{
void onCallFromFragB();
}
}
Now you can reference the parent activity by calling getActivity on onAttach()
public void onAttach(Context context) {
super.onAttach(context);
....
activity = (FragBListener) getActivity();
}
Now that you have a reference to the activity, you can call the implemented method from the interface. You can really call any public method from the parent activity really as long as you don't typecast it to the listener, I just prefer it that way.
Now calling a method inside of the Fragment from the activity is even easier. Like so:
FragB fragB= (FragB) getSupportFragmentManager().findFragmentById(R.id.imager);
if(fragB != null){
// FragB is in view
// call it's methods
}
This way your fragments will be self contained and the communication is done via the activity so you won't really have to worry about the scenario. You just want to make sure that you call the public methods on the fragments as long as they are not null (in the layout).
For reference, you can see this.
Ok so with everything I have mentioned so far, here is what you can do.
- Load Fragment B from activity.
- When Fragment B's button is clicked. Call the activity's method that replaces Fragment B with Fragment B1.
- The onItemClickListener of B1 can then call the activity's method passing in the String so that the activity can replace B1 with B with the TextView set to the String that you just passed in.
If you do not wish to mess around with the interface, you can also just typecast the activity. For example, if the activity is MainActivity,
((MainActivity) getActivity()).[any public method]
is also possible when calling from one of its fragments.