Creating Alert Dialogs in Android

Android supports various forms of dialogs. Dialogs include Alert Dialogs, Progress dialogs, time picker dialogs and extend support to custom dialogs. Alert dialogs are used to prompt user or show simple message of validation.

Let’s begin with Android Alert Dialogs and see how to implement it.

Design Alert Dialog

Alert dialogs commonly contains messages to display as a validation or prompt user for some action. You can use alert dialog builder class to construct alert dialog. Lets see what kind of actions can be added in Alert Dialog.

  • Prompt user to respond with positive or negative action.
  • Pick single or multiple item from list displayed in the dialog.
  • Display some information to the user
  • Select option to confirm from a set of options.

Alert Dialog Builder

Steps to create a dialog builder:

  • Create dialog builder object
  • Set title, message and other parameters like
  • Build dialog from builder object
  • Show dialog

Prompt message in alertdialog android

Design Prompt Dialog in XML

We can inflate  custom view instead of the default message view of Alert Dialog. Now let’s design own custom alert message layout in xml.

Create dialog view layout.

Create custom alert dialog using the same code and set view with new created view.

Create custom alert dialog in android

Dialog Fragments

We will see now how to create alert dialog using Dialog Fragments. Alert dialog will be managed by a fragment as DialogFragment contains object of dialog.

Let’s check how we will implement the above alert dialog example with DialogFragments. Create a new class and extend it from DialogFragment. DialogFragment provides a function onCreateDialog which returns dialog.

From the activity we can now call our dialog fragment.

Toast Messages

Toast is similar to alert dialog with a message. The difference is that toast do not have any user interaction and is displayed only for a short time before it hides away.

Toast alert example in android

Toasts can be used outside activity as it takes any context to create alert. Therefore toast alerts can be displayed from services, receivers etc.

 

Leave a Reply