Should we be using setTargetFragment()? I thought Fragments should not be communicating with each other
The android developer tutorials recommend me using the host activities of fragments to pass around data and whatnot, so why is there a set/get target fragment method?
My application thus far contains a host activity, and a fragment, which has a button that launches a
DialogFragment, in which there is a button that launches ANOTHER
setTargetFragment/getTargetFragment has made this whole ordeal somewhat confusing though, so I am thinking of reimplementing to let my main activity handle
DialogFragment.show methods through my main fragment’s custom interface.
Is this the right way of thinking? Or is there no harm in using
setTargetFragment? Can anyone provide good and bad examples of using it?
2 Solutions collect form web for “Should we be using setTargetFragment()? I thought Fragments should not be communicating with each other”
I don’t think there is implicit harm in using setTargetFragment, however, I would only use it in very specific circumstances. For example, if the target fragment is only going to ever be used by the fragment (taking into account object reuse and designing your classes to be reusable when possible) and even then, sparingly.
By using them too much, you will end up with what you’re seeing – confusing code that is hard to follow and maintain. On the outset, by marshaling everything through your activity you maintain a “flat” hierarchy that is simple to follow and maintain.
I think the decision to use setTargetFragment or not is a coding-style/philosophical one that, with wisdom and experience, it “feels” right or wrong. Maybe on your case, by evidence that you are questioning your older code, you are gaining that wisdom 🙂
Also, you may end up with exception of no target fragment found in fragment manager. This happens if after rotation (or other config change) your target fragment will not be readded to the fragment manager by the time when caller fragment will be adding.
Imagine you have some sort of Confirmation fragment which you add from
MainFragment as so:
ConfirmationFragment frag = new ConfirmationFragment(); frag.setTargetFragment(this, 0); getFragmentManager().beginFragmentTransaction().add(R.id.container, frag).commit();
Now on some confirmation button click you invoke a method from
MainFragment by calling:
This is pretty and simple, but if you will rotate the screen and for some reason
ConfirmationFragment will be added to
MainFragment, exception will be thrown, stating that target fragment is not found in the fragment manager