Sometimes, you’ll want to show a more unique or complex dialog to your users. By creating a custom dialog, you can define your own layout to display in the main content area of the dialog.
To create the Custom Dialog, open dialog_fruit.xml. This simple layout contains a TextView and an ImageView.
To implement the custom layout in a dialog, you need to extend DialogFragment() and override onCreateDialog(). In the project, open CustomFruitDialog.kt. You’ll see already declared onCreateDialog() which isn’t doing anything custom right now. But that’s about to change. Replace:
super.onCreateDialog(savedInstanceState)
with the following code:
activity?.let {
val inflater = it.layoutInflater
AlertDialog.Builder(it)
.setView(inflater.inflate(R.layout.dialog_fruit, null))
.setPositiveButton(R.string.dialog_fruit_close) { _, _ ->
listener?.onDialogButtonClicked()
}
.create()
} ?: throw IllegalStateException("Activity cannot be null")
This code first checks that DialogFragment has Activity into which it can be inflated, and throws an error if Activity is null. In this case, the app wouldn’t be able to display the dialog on the screen.
This time, the code uses the Android AlertDialog.Builder class directly to create the custom dialog. setView() inflates the custom layout into the dialog, and setPositiveButton() makes use of the standard dialog buttons. You aren’t required to use the dialog buttons if your custom layout has its own built in.
The positive button’s click listener calls onDialogButtonClicked() from a custom interface, which has not yet been defined.
In the same file, find the Listener interface and add the following code in place of TODO:
fun onDialogButtonClicked()
This is an interface method you can implement in any class where you wish to show this custom dialog. In this way, you can change the behavior of the positive button depending on the context of where the dialog is shown.
Showing the Custom Dialog $[==]
Now, you need to show the dialog. Go back to MainActivity.kt and find the card with ID card_mystery. This card already has a click listener assigned that calls loadSurpriseDialog(), which has not yet been implemented.
Add the following code in loadSurpriseDialog():
CustomFruitDialog().apply {
listener = object : CustomFruitDialog.Listener {
override fun onDialogButtonClicked() {
dismiss()
}
}
}.show(supportFragmentManager, TAG_FRUIT_DIALOG)
This creates an instance of your newly defined CustomFruitDialog, implements the click listener to dismiss the dialog and shows the dialog. Build and run. Tap the Mystery fruit card to see the custom dialog.