Android - getTargetFragment and setTargetFragment - What are they used for

j2emanue picture j2emanue · Sep 1, 2013 · Viewed 34.4k times · Source

I tried searching but i'm still a little lost. I usually do fragment to fragment communication through an Activity via interfaces or a BroadcastReceiver.

Anyway, my question is what is the use of getTargetFragment? Can someone provide a use case or just a quick example so i can comprehend its usage?

Answer

kandinski picture kandinski · Sep 1, 2015

Use case = 2 fragments hosted by the same activity.

Where startActivityForResult() establishes a relationship between 2 activities, setTargetFragment() defines the caller/called relationship between 2 fragments.

setTargetFragment(target) lets the "called" fragment know where to send the result. onActivityResult() is called manually in this case.

public class Caller extends Fragment
     Fragment called = Called.newInstance()
     called.setTargetFragment(this)

public class Called extends DialogFragment
   intent = amazingData
   getTargetFragment().onActivityResult(getTargetRequestCode(), resultCode, intent)