Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 DialogFragment. Using 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?

like image 461
Toni_Entranced Avatar asked Sep 22 '13 16:09

Toni_Entranced


2 Answers

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:

((MainFragment)this.getTargetFragment()).onUserSelectedGoodButton();

This is pretty and simple, but if you will rotate the screen and for some reason ConfirmationFragment will be added to FragmentManager before MainFragment, exception will be thrown, stating that target fragment is not found in the fragment manager

like image 66
Max Ch Avatar answered Oct 11 '22 23:10

Max Ch


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 :)

like image 40
nomachinez Avatar answered Oct 11 '22 23:10

nomachinez