Android Developer Tutorials and Blog

In this tutorial I’ll show you how to create a dialog fragment that can be used for general purpose dialogs where you want to show the user a message and just have one option for them to acknowledge the message.

The unique thing about this tutoral is you can add an object to your dialog and this is passed back to the calling activity. This allows you to use the Dialog on custom views like a ListView, when the user presses the item the dialog is popped up, when the user acknowledges this dialog the activity will receive that item from your list.

In short this dialog is kind of like an Android Intent. You can add an ‘extra’ to the dialog that is passed back when the dialog is acknowledged.

Ok Here .. we .. go

First, no need to change your AndroidManifest.xml woo. Just add a button to the Activity to show the dialog. This is the simplest example, you can use this dialog anywhere (examples at the bottom), so anywhere your onClick imagination can take you. The onClick is actually declared in the XML layout file:

Notice that the Activity implements our Dialog’s onClick listener. This is a callback for when the Dialog button is pressed. The Interface uses generics to allow us to state what type of data we want to pass to and from the Dialog.

Skipping forward a bit, you can imagine a scenario where you have a bunch of users in a listview, when one of these users is clicked you would like to delete that user from your database, the Activity should deal with the delete but the listview wants to show the dialog. Therefore the dialog needs to pass back the details of the user that was pressed. This is where generics come in. When we create our dialog we use generics to tell the dialog we will be passing round ‘UserDetails’ objects.
Here is one of those objects it’s pretty simple:

I don’t think I’ve explained this too well but it’s kind of a tough one without me rambling, hopefully if you check out the example source project and run it up, you can see what is going on and find it useful.

I wrote this DialogFragment for ease of use, you can create multiple dialogs without having to write loads of code over and over. Here are a few examples: