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.

setTargetFragment-

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.

Parameters
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).

getTargetFragment-

Fragment getTargetFragment ()

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

Returns
Fragment

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.

Example:-

First Fragment-

Bundle bundle = new Bundle();
bundle.putString(AppConstant.data1, data1);
bundle.putString(AppConstant.data2, data2);

SecondFragment fragment = new SecondFragment();
fragment.setArguments(bundle);

//This is required to communicate between two framents. Similar to startActivityForResult
fragment.setTargetFragment(FragmentFirst.this, AppConstant.REQ_CODE_SECOND_FRAGMENT);

FragmentManager fragmentManager = getFragmentManager();
fragment.show(fragmentManager, AppConstant.FRAGMENT_NAME);

Callback of Second Fragment on First Fragment-

@Override
public void onActivityResult(int requestCode, int resultCode, Intent intent) 
{
    super.onActivityResult(requestCode, resultCode, intent);
    if (resultCode == Activity.RESULT_OK)
    {
        if (requestCode == AppConstant.REQ_CODE_SECOND_FRAGMENT)
        {
           String secondFragmentData= intent.getStringExtra(AppConstant.INTENT_KEY_SECOND_FRAGMENT_DATA);
        }
    }

}

Second Fragment-

Getting the Fragment:-

Intent intent = new Intent();
intent.putExtra(AppConstant.INTENT_KEY_SECOND_FRAGMENT_DATA, secondFragmentData);

Fragment fragment = getTargetFragment();
fragment.onActivityResult(AppConstant.REQ_CODE_SECOND_FRAGMENT, Activity.RESULT_OK, intent);

Leave a Reply