Search code examples
androidandroid-fragmentsandroid-fragmentactivity

Calling DialogFragment from Fragment (not FragmentActivity)?


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?


Solution

  • 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;
        }
    }