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 {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}

@Override
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.remove(prev);
}
ft.addToBackStack(null);
DialogFragment dialogFragment = new MyCustomDialogFragment();
dialogFragment.show(ft, "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:

dialogFragment.dismiss();

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 xabaras.it (in Italian).

One clap, two clap, three clap, forty?

By clapping more or less, you can signal to us which stories really stand out.