Implement a Material Dialog Fragment for Android

As we develop our apps, one of our goals is to follow the recommended guidelines for the target platforms. Material Design provides guidelines for mobile and web application, and is a recommended guidelines for Android applications.

The Material design site provides guidelines for design and behavior of application components. This site provides implementations of several of these. For other components, guidelines and specifications are provided to allow developers to do the implementation themselves.

The implementation for the Material Alert Dialog is provided in the Material library, enabling developers to create a dialog styled with the Material guidelines. Unfortunately, there isn’t an implementation for a Material dialog fragment. DialogFragments are a fragment subclass that is designed for hosting dialogs. One benefit of this is that it manages the dialog and its lifecycle when configuration changes occur.

As we want to implement dialogs with the new Material guidelines, and we want to correctly handle the application lifecycles, we looked at implementing a dialog fragment that created Material dialogs. We created a new class that extends AppCompatDialogFragment, that creates a MaterialAlertDialog in onCreateDialog, as seen below


class MaterialDialogFragment : AppCompatDialogFragment() {
    override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
        val builder =
            MaterialAlertDialogBuilder(requireContext(),
                R.style.ThemeOverlay_MaterialComponents_MaterialAlertDialog)


        // Populate dialog

        return builder.create()
    }

}