Step #3: Defining the Dialog Content

We can now start to use those arguments to populate the dialog. There are a couple of approaches to defining what the dialog contains. We will take the simplest one: use AlertDialog.Builder to create a standard Android dialog.

With that in mind, add args and onCreateDialog() to ErrorDialogFragment:

class ErrorDialogFragment : DialogFragment() {
  private val args: ErrorDialogFragmentArgs by navArgs()

  override fun onCreateDialog(savedInstanceState: Bundle?): Dialog {
    return AlertDialog.Builder(requireActivity())
      .setTitle(args.title)
      .setMessage(args.message)
      .setPositiveButton(R.string.retry) { _, _ -> onRetryRequest() }
      .setNegativeButton(R.string.cancel) { _, _ ->  }
      .create()
  }

  private fun onRetryRequest() {
    // TODO
  }
}

The args property is like those we have in DisplayFragment and EditFragment, so we can get the values sent to us by whatever fragment wants to display the dialog.

onCreateDialog() needs to return a Dialog object; AlertDialog is a subclass of Dialog. Dialog knows how to create floating windows, while AlertDialog styles one of those in a typical Android fashion. So, we create an AlertDialog.Builder, configure it, and use build() to create the AlertDialog to return.

The configuration includes:

Those string resources do not exist yet, so you will need to add them:

  <string name="cancel">Cancel</string>
  <string name="retry">Retry</string>

We will fill in that onRetryRequest() function a bit later in this chapter.


Prev Table of Contents Next

This book is licensed under the Creative Commons Attribution-ShareAlike 4.0 International license.