Android – Show dialog from fragment

androidandroid-dialogandroid-dialogfragment

I have some fragments that need to show a regular dialog. On these dialogs the user can choose a yes/no answer, and then the fragment should behave accordingly.

Now, the Fragment class doesn't have an onCreateDialog() method to override, so I guess I have to implement the dialogs outside, in the containing Activity. It's ok, but then the Activity needs to report back the chosen answer somehow to the fragment. I could of course use a callback pattern here, so the fragment registers itself at the Activity with a listener class, and the Activity would report back the answer thru that, or something like that.

But this seems to be quite a big mess for a simple task as displaying a "simple" yes-no dialog in a fragment. Also, this way my Fragment would be less self-contained.

Is there some cleaner way to do this?

Edit:

The answer to this question doesn't really explain in detail how one should use DialogFragments to display dialogs from Fragments. So AFAIK, the way to go is:

  1. Display a Fragment.
  2. When needed, instantiate a DialogFragment.
  3. Set the original Fragment as the target of this DialogFragment, with .setTargetFragment().
  4. Show the DialogFragment with .show() from the original Fragment.
  5. When the user chooses some option on this DialogFragment, notify the original Fragment about this selection (e.g. the user clicked 'yes'), you can get the reference of the original Fragment with .getTarget().
  6. Dismiss the DialogFragment.

Best Answer

I must cautiously doubt the previously accepted answer that using a DialogFragment is the best option. The intended (primary) purpose of the DialogFragment seems to be to display fragments that are dialogs themselves, not to display fragments that have dialogs to display.

I believe that using the fragment's activity to mediate between the dialog and the fragment is the preferable option.