📜 ⬆️ ⬇️

Returning the execution result from the DialogFragment to the Fragment bypassing the Activity

Introduction


In this post, I will show how you can pass events from DialogFrament to the caller Fragment bypassing the Activity.

The official Dialogs Guide has a section called PassingEvents . It tells you how to return the result of a DialogFragment to the calling Activity. For this, an additional interface is created. Activity implements this interface, and DialogFrament has a link to Activity.

If the initiator of the DialogFragment call is another Fragment, then in this approach we will have to first send the result to the Activity, and then from the Activity to the Fragment interested in the data. From here and minuses:


Fortunately, the Fragment class has 3 methods that allow realizing the transfer of events from one fragment to another fragment bypassing the Activity. It:

The essence of the method


Calling fragment:

Called fragment:

Below is a sample code. For simplicity, left only the relevant parts of the article.
')
Calling fragment:

public class HostFragment extends Fragment { private static final int REQUEST_WEIGHT = 1; private static final int REQUEST_ANOTHER_ONE = 2; public void openWeightPicker() { DialogFragment fragment = new WeightDialogFragment(); fragment.setTargetFragment(this, REQUEST_WEIGHT); fragment.show(getFragmentManager(), fragment.getClass().getName()); } @Override public void onActivityResult(int requestCode, int resultCode, Intent data) { super.onActivityResult(requestCode, resultCode, data); if (resultCode == Activity.RESULT_OK) { switch (requestCode) { case REQUEST_WEIGHT: int weight = data.getIntExtra(WeightDialogFragment.TAG_WEIGHT_SELECTED, -1) //   //... break; case REQUEST_ANOTHER_ONE: //... break; //  requestCode } updateUI(); } } } 

Called fragment:

 public class WeightDialogFragment extends DialogFragment { //     public static final String TAG_WEIGHT_SELECTED = "weight"; @NonNull @Override public Dialog onCreateDialog(Bundle savedInstanceState) { LayoutInflater inflater = getActivity().getLayoutInflater(); View view = inflater.inflate(..., null); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setView(view) .setPositiveButton("Ok", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { //   Intent intent = new Intent(); intent.putExtra(TAG_WEIGHT_SELECTED, mNpWeight.getValue()); getTargetFragment().onActivityResult(getTargetRequestCode(), Activity.RESULT_OK, intent); } }); return builder.create(); } } 

Conclusion


The minuses listed at the beginning of this article are absent. Only two interacting elements know about each other. For the rest, these are already unknown implementation details.

I would like to know about this version of the implementation even when studying the official guide on the dialogues. I learned later thanks to StackOverflow .

Source: https://habr.com/ru/post/259805/


All Articles