Calling DialogFragment from Fragment (not FragmentActivity)?

Elie Page picture Elie Page · Sep 17, 2014 · Viewed 48.2k times · Source

I do have a FragmentActivity which contains a Fragment list (with methods to navigate between them). In one of those fragments I need to call a DialogFragment to display a "zoom" on a Picture contained in that fragment.

But it seems that you can't call a DialogFragment directly from a Fragment.

Is there any way to get some kind of "callback" to the FragmentActivity to make this display the DialogFragment over the fragment.

Or simply a "glitch" to call it directly from the Fragment.

If that is the case what are my options?

Answer

Manitoba picture Manitoba · Sep 17, 2014

When you create a new Dialog, you can simply call it using this (very) simple method from a Fragment.

DialogFragment dialog = DialogFragment.instantiate(getActivity(), "Hello world");
dialog.show(getFragmentManager(), "dialog");

If you want to use your own dialog, please use that kind of code.

public class MyDialogFragment extends DialogFragment
{
    //private View pic;

    public MyDialogFragment()
    {
    }

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState)
    {
        View view = getActivity().getLayoutInflater().inflate(R.layout.fragment_my_dialog, new LinearLayout(getActivity()), false);

        // Retrieve layout elements
        TextView title = (TextView) view.findViewById(R.id.text_title);

        // Set values
        title.setText("Not perfect yet");

        // Build dialog
        Dialog builder = new Dialog(getActivity());
        builder.requestWindowFeature(Window.FEATURE_NO_TITLE);
        builder.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
        builder.setContentView(view);
        return builder;
    }
}