Reusing dialog boxes

In the Android developer guide there is an extensive review on how to use dialogs in Android. In short the preferred method is to override onCreateDialog and onPrepareDialog for each activity and implement your logic there. I don’t like it, mainly because it spreads your logic, users who read your code “don’t understand” what happens when you execute showDialog, it’s much harder to follow.

I’ve decided to put all of my dialog box in one place, a factory method I created, which returns dialog boxes which I can reuse.

Here is a nice example of AlertDialog:

public class DialogBoxFactory {
	 * Create a simple dialog box with OK button and a message.
	 * @param message - Message to show.
	 * @param ctx - Context on which dialog will be shown.
	 * @return Alert dialog created.
	public static AlertDialog getDialog(String message, Context ctx) {
		AlertDialog.Builder builder = new AlertDialog.Builder(ctx);
    	       .setPositiveButton("OK", new DialogInterface.OnClickListener() {
    	           public void onClick(DialogInterface dialog, int id) {
    	return builder.create();

and now how to use

String error = e.getMessage();
AlertDialog dialog = DialogBoxFactory.getDialog("Unable to authenticate: " + error, activity);

Pay attention that I’m using setOwnerActivity in order to set the owner of the dialog box and don’t forget to show it at the end.

That’s it. Makes my code more readable.


1 Comment

Filed under Uncategorized

One response to “Reusing dialog boxes

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google+ photo

You are commenting using your Google+ account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )


Connecting to %s