Creating a custom Dialog with DialogFragment

Ever since android was release, creating a dialog with a custom layout has always been tricky, since Android Dialog class was not meant to do so.

Fortunately with API level 11 the Android team released the DialogFragment which subsequently was added to the support library making it available for all targets.

A DialogFragment is a fragment showing a dialog window floating on its activity’s one. Since it’s a fragment it integrates into the activity’s lifecycle and ensures that what’s happening in the dialog window remains consistent (while dialogs where generally autonomous entities).

Creating a custom Dialog with DialogFragment is pretty simple, you just need to extend the DialogFragment class like this:

public class MyCustomDialogFragment extends DialogFragment {
 public void onCreate(Bundle savedInstanceState) {
 public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.fragment_my_custom_dialog, container, false);
        // Do all the stuff to initialize your custom view
        return v;

Now all you have to do is to implement the code to show the dialog from inside your activity or fragment.

Since DialogFragment is an actual fragment you will only need to create a fragment transaction and call the show method of MyCustomDialogFragment:

FragmentTransaction ft = getFragmentManager().beginTransaction();
Fragment prev = getFragmentManager().findFragmentByTag("dialog");
if (prev != null) {
ft.addToBackStack(null);DialogFragment dialogFragment = new MyCustomDialogFragment();, "dialog");

The show method will add the DialogFragment to the transaction and handle the commit.

Though the first line and last two would be enough to show the custom dialog, you will notice that a few lines of code have been added after the FragmentTransaction creation.

This code serves to ensure that no other instance of the dialog will still be visible.

To dismiss the dialog you will only need to do the following:


This is only a smattering of how to use the DialogFragment, a more accurate documentation can be found on the Android Developer Portal.

This story is also available on (in Italian).



邮箱地址不会被公开。 必填项已用*标注