Fragment to Fragment Communication

Communication Between Fragments

We can communicate from one Fragment to another Fragment and receive callback from calling Fragment to caller Fragment by using a standard method setTargetFragment() and getTargetFragment().

Scenario – We are in a Fragment and want to open a Dialog Fragment on top of Fragment. On Dialog Fragment, we do some task and then need to send data back to the first fragment and close the Dialog Fragment.


void setTargetFragment (Fragment fragment, int requestCode)

Optional target for this fragment. This may be used, for example, if this fragment is being started by another, and when done wants to give a result back to the first. The target set here is retained across instances.

fragment Fragment: The fragment that is the target of this one.
reqCode int: Optional request code, for convenience if you are going to call back with onActivityResult(int, int, Intent).


Fragment getTargetFragment ()

Return the target fragment set by setTargetFragment (Fragment fragment,int requestCode).


Working Flow:-

  1. If we want to communicate from one fragment to another fragment then from First fragment  we have to use setTargetFragment (FirstFragment instance ,RequestCode).
  2. After that use show() method of fragment.
  3. On Second Fragment we have to use getTargetFragment() which return fragment instance.
  4. Then use onActivityResult (reqCode ,Activity.RESULT_OK, intent). As per given in example Fragment Second. The callback of second Fragment can be received in override method onActivityResult of Fragment First.


First Fragment-

Callback of Second Fragment on First Fragment-

Second Fragment-

Getting the Fragment:-

Leave a Reply