Dialogs in Android: Practical Guide

Last updated 106 days ago by Vasiliy Zukanov

android

Dialogs are among the most basic building blocks in Android applications. They allow you to show important notifications to your users, quickly capture users’ input, expand screens’ functionality and much more. Unfortunately, as basic as they are, in Android dialogs aren’t that simple to implement.

In this post I’ll try to summarize what you need to know in order to use dialogs safely and efficiently in your Android apps.

Dialog vs DialogFragment

The very first question to address in respect to Android dialogs is: “should I use Dialog or DialogFragment to implement dialogs?”.

Initially there was just Dialog class in Android. If you’d like to have dialogs, you’d use it and that’s it. [Well, with the exception of developers who implemented dialogs infrastructure manually by using View subclasses, but I wouldn’t recommend this approach.] Then, when Fragments came around, DialogFragment was introduced. This is basically a Fragment that can be used as a dialog.

I recommend using DialogFragment over Dialog due to the following reasons:

  • DialogFragment is automatically re-created after configuration changes and save & restore flow
  • DialogFragment inherits full Fragment’s lifecycle

Automatic re-creation is very handy because you probably want most of your dialogs to remain on the screen if, for example, the device is rotated. With Dialog you’d need to take care of this manually because Dialog instances are dismissed when their host Activity is destroyed. DialogFragment instances are destroyed too, but then Android re-creates them for you after the host Activity is re-created.

The point about full Fragment’s lifecycle might be a bit surprising because Fragment’s lifecycle is a very complicated topic. It’s rarely brought up as something positive. However, by having a full lifecycle, DialogFragment instances are much more suited to be fully-capable controllers. This might be not that important for simple dialogs with just one or two buttons, but becomes very handy when you need to build complex dialogs that, for example, allow the user to invoke some long-running operation, show progress indication and then display the results.

So, in my opinion it’s best to implement your dialogs using DialogFragment instances.

How to Implement DialogFragment

There are many good tutorials about DialogFragment on the internet, so I won’t go into much details here. However, I’d like to point out several nuances and discuss some high-level design considerations.

There are two ways to define DialogFragment’s UI:

  • return View hierarchy from onCreateView() method (the standard Fragment approach)
  • constuct a Dialog and return it from onCreateDialog()

The second approach allows you to reuse existing subclasses of Dialog in Android (e.g. AlertDialog), as well as third-party Dialog libraries.

Read full Article