Select Page

We need AlertDialog to get user feedback, confirm, alert .You can find basic details about AlertDialog in my previous post.

While playing with AlertDialog this utility class will help you more.

What is AlertDialogHelper ?

AlertDialogHelper which is the utility class contains the set of utility methods to show dialogs and returns their clicks using callback methods.

How to use ?

AlertDialogHelper : Used to show AlertDialog.

AlertDialogListener : This is a callback interface which returns the user selection.

AlertDialogHelper :

In this class, showAlertDialog is the method used to show the dialog. It is an overloaded method. Based on the input it will show the dialog with the title, message, action buttons( positive, negative, neutral).

/**
* Displays the AlertDialog with 3 Action buttons
* you can set cancelable property
*/
public void showAlertDialog(String title,String message,String positive,
String negative,String neutral,final int from,boolean isCancelable)

title : The title of the alert dialog

message : Message to be displayed in the alert dialog

positive,negative,neutral : Caption of the action buttons

from : Request code

isCancelable : Property that the dialog can be cancelled or not

AlertDialogListener :

It is the callback interface which listens to the user click of the action buttons.

public interface AlertDialogListener
{
public void onPositiveClick(int from);
public void onNegativeClick(int from);
public void onNeutralClick(int from);
}

Before implementing this, you need to create an instance for the class ” AlertDialogHelper “.

AlertDialogHelper alertDialogHelper;
alertDialogHelper = new AlertDialogHelper(this);

Second, call the relevant method based on your need. The following steps help you to show the dialog.

// Request code – 1
alertDialogHelper.showAlertDialog("Draft","Discard draft ?","Discard","Cancel",1,false);

Third, you need to include AlertDialogListener interface into your activity,and also implement the needed methods.

public class AlertDialogSampleActivity extends AppCompatActivity implements AlertDialogHelper.AlertDialogListener
{
// Callback Methods
@Override
public void onPositiveClick(int from) {
Toast.makeText(getApplicationContext(), "Positive Click from :"+from, Toast.LENGTH_LONG).show();
}
@Override
public void onNegativeClick(int from) {
Toast.makeText(getApplicationContext(), "Negative Click from :"+from, Toast.LENGTH_LONG).show();
}
@Override
public void onNeutralClick(int from) {
Toast.makeText(getApplicationContext(), "Neutral Click from :"+from, Toast.LENGTH_LONG).show();
}
}
View Gist

 

 

Elsewhere

Jaison Fernando

Android Developer at NFN Labs
Elsewhere