Android: remove confirmation dialog window

Another tutorial today is how to build confirmation dialog window. Android provides API for that. What I am going to build here is dialog window triggered by some action (button click) and react on confirm or cancel button click:

Confirmation dialog example

1. Create dialog’s id constant

This is simply dialog’s ID. it should be unique among any other dialog window that is handled by current activity. I set it like that:

protected static final int DIALOG_REMOVE_CALC = 1;
protected static final int DIALOG_REMOVE_PERSON = 2;

2. Build dialog

I use this method to build dialog window:

private Dialog createDialogRemoveConfirm(final int dialogRemove) {
	return new AlertDialog.Builder(getApplicationContext())
	.setIcon(R.drawable.trashbin_icon)
	.setTitle(R.string.calculation_dialog_remove_text)
	.setPositiveButton(R.string.calculation_dialog_button_ok, new DialogInterface.OnClickListener() {
		public void onClick(DialogInterface dialog, int whichButton) {
			handleRemoveConfirm(dialogRemove);
		}
	})
	.setNegativeButton(R.string.calculation_dialog_button_cancel, null)
	.create();
}

AlertDialog builder pattern is utilized here. I do not handle NegativeButton click action – by default the dialog is just being hidden. If dialog’s confirm button is clicked, my handleRemoveConfirm callback is called and action is performed based on dialog’s ID:

protected void handleRemoveConfirm(int dialogType) {
	if(dialogType == DIALOG_REMOVE_PERSON){
		calc.removePerson();
	}else if(dialogType == DIALOG_REMOVE_CALC){
		removeCalc();
	}
}

3. Show Dialog

I show dialog after my remove button click. The showDialog(int) is Android’s Activity’s method:

OnClickListener removeCalcButtonClickListener = new OnClickListener() {
	public void onClick(View v) {
		showDialog(DIALOG_REMOVE_CALC);
	}
};

the showDialog(int) method calls onCreateDialog (also defined in Activity’s class). Override it and tell your app what to do if the showDialog was requested:

@Override
protected Dialog onCreateDialog(int id) {
	switch (id) {
	case DIALOG_REMOVE_CALC:
		return createDialogRemoveConfirm(DIALOG_REMOVE_CALC);
	case DIALOG_REMOVE_PERSON:
		return createDialogRemoveConfirm(DIALOG_REMOVE_PERSON);
	}
}

Here I have two dialogs possible. Both are remove dialogs, however their confirm button handlers are different.

Did I help you?
I manage this blog and share my knowledge for free sacrificing my time. If you appreciate it and find this information helpful, please consider making a donation in order to keep this page alive and improve quality

Donate Button with Credit Cards

Thank You!

2 thoughts on “Android: remove confirmation dialog window

Give Your feedback: