0

Having Fragment A and B, B is kinda of extended A. The UI data update from B need to store back in A and A's UI makes decision whether to save to database.

So A is put on the backstack first, then at some time it needs B and B is put on the backstack and in the holder with 'replace()'.

Passing data to B could be don by argument. How to pass data back from B fragment to the A fragment (if A is 'replaced()' by B on the holder and currently not showing or 'existing')?

Bundle args = new Bundle();
args.putSerializable(TAG_MY_CLASS, myClass);
Fragment bFrgmt = new B();
bFrgmt.setArguments(args);
getFragmentManager()
    .beginTransaction()
    .replace(R.id.holder, bFrgmt, TAG_B_FRAGMENT)
    .addToBackStack(TAG_B_FRAGMENT).commit();
lannyf
  • 9,865
  • 12
  • 70
  • 152
  • Usually the communication between Fragments is done via Activity (pattern Observer). So Fragment that is active tells its Activity that some action is happend (via interface) and Activity can tell it to Fragment1 – alla Nov 16 '16 at 20:38
  • thanks alla! I guess my question is about what is the best way to deliver from B to A when B is still on the screen and A is in unknown state (has been replaced by B on same 'holder'). Was thinking maybe catch the B popstack event, and then since OS will bringing back in the A in the 'holder' so that we can deliver the data to A at that time. Is there better way? – lannyf Nov 16 '16 at 20:49

1 Answers1

2

From Developers website:

Often you will want one Fragment to communicate with another, for example to change the content based on a user event. All Fragment-to-Fragment communication is done through the associated Activity. Two Fragments should never communicate directly.

First send data from fragment to activity, then receive this data in activity, then from Activity you can send data to Fragment with intent and to receive in fragment onCreateView method.

You can communicate among fragments with the help of its Activity. You can communicate among activity and fragment using this approach.

M. Tarek
  • 21
  • 5