Search code examples
androidandroid-fragmentsandroid-dialogfragment

How to set the title of DialogFragment?


This should be a simple task, but for some reason I can find a way to set the title of a DialogFragment. (I am setting the dialog contents using onCreateView overload).

The default style leaves a place for the title, but I can't find any method on the DialogFragment class to set it.

The title is somehow magically set when the onCreateDialog method is used to set the contents, so I wonder if this is by design, or there is a special trick to set it when using the onCreateView overload.


Solution

  • You can use getDialog().setTitle("My Dialog Title")

    Just like this:

    public static class MyDialogFragment extends DialogFragment {
        ...
        @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
            // Set title for this dialog
            getDialog().setTitle("My Dialog Title");
    
            View v = inflater.inflate(R.layout.mydialog, container, false);
            // ...
            return v;
        }
        // ...
    }