Wednesday, October 4, 2017

Android AlertDialog

How to display a delete confirmation box?

A simple method is to use AlertDialog that quickly provides the "CANCEL" and "OK" along with your custom confirmation message.



An example within a Fragment class where a user click's the Delete button which calls the deleteConfirmation( ) function with the title or name of item to be delete.

1:  private void deleteConfirmation(String title){  
2:    AlertDialog.Builder alert = new AlertDialog.Builder(getContext());  
3:    alert.setTitle("Delete");  // Declare the title
4:    alert.setMessage("Are you sure you want to delete \n"+title+"?");  // Set message below title
5:    alert.setIcon(R.mipmap.ic_delete);  // Set the icon at top left
6:    alert.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {  
7:      public void onClick(DialogInterface dialog, int which) {  
8:        // continue with delete  
9:        MainActivity.confirmDelete=true;  
10:        delete();  
11:      }  
12:    });  
13:    alert.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {  
14:      public void onClick(DialogInterface dialog, int which) {  
15:        // close dialog  
16:      }  
17:    });  
18:    MainActivity.confirmDelete=false;  
19:    alert.show();  
20:  }  

Note 1:
The Dialog class is the base class to AlertDialog that makes the user take an action before returning back to the Fragment or Activity. This is known as a Modal Event. Other example of Dialog class are DatePickerDialog and TimePickerDialog.

If used for Android API 25 and onward, the import statement is

import android.app.AlertDialog;

for API 11 to below API 25 use

import android.support.v7.app.AlertDialog;

Note 2:
There are 3 type of buttons that can be added (in the example above, only 2 are added) to an AlertDialog. Only one of each type can be added using the following methods;

alert.setPositiveButton
alert.setNegativeButton
alert.setNeutralButton

List can be added to AlertDialog if required.

Note 3:
There are several ways to pass message or status to the Activity or Fragment that created/launched the AlertDialog. In the example above, a static variable is declared in the MainActivity and values are changed base on button clicked.

In MainActivity.java

public static boolean confirmDelete=false;

Note 4:
To further customise the AlertDialog look, a resource file (XML) can be created and assigned with the method

LayoutInflater inflater = getActivity().getLayoutInflater();
alert.setView( inflater.inflate(R.layout.customDialog, null) )


Done.

Blog Archive