Categories
android android-fragments communication

Android – getTargetFragment and setTargetFragment – What are they used for

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?

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)