Search code examples
androidandroid-fragmentsandroid-dialogfragment

Why does Android have setTargetFragment() for communicating data back from DialogFragments?


The official documentation says:

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.

However, I have come across multiple articles talking about using setTargetFragment() to send data from a DialogFragment to a caller fragment.

This seems like an anti-pattern to me since this minimizes the need to go through an activity.

Can anyone explain the rational behind introducing setTargetFragment() and getTargetFragment()?


Solution

  • Architectures aren't always 100% clean. Something as big as Android is written by dozens of developers, each with their own point of view. Sometimes those points differ, and sometimes that shows up in either unsuspected API calls existing or documentation not matching up.

    Also, there's a difference between sibling fragments and child fragments. A fragment shouldn't know anything about its siblings. But if a fragment needs to launch another fragment and handle its result (just like it may an activity) then its perfectly acceptable for the fragment to do it directly without needing to involve its activity. That's what setTargetFragment is for.