I have the following AlertDialog:
AlertDialog.Builder dialogBuilder = new AlertDialog.Builder(mContext);
dialogBuilder.setTitle(R.string.title);
dialogBuilder.setMessage(mContext.getString(R.string.message));
dialogBuilder.setPositiveButton(R.string.positive, new MyOnClickListener());
dialogBuilder.setNegativeButton(R.string.negative, new MyOnClickListener());
dialogBuilder.show();
with this ClickListener
public static class MyOnClickListener implements DialogInterface.OnClickListener{
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}
I would expect the dialog to be closed, when clicking on either of the buttons, but the dialog stays open instead.
I debugged the onClick method and the line
dialog.dismiss()
is being executed, but nothing happens.
Where am I going wrong or how can I fix this?
Declare your AlertDialog
at the top like:
private AlertDialog myAlertdialog;
then replace your dialogBuilder.show();
with
myAlertDialog = dialogBuilder.create();
myAlertDialog.show();
then you can call myAlertDialog.dismiss();
Try this
AlertDialog alertDialog = new AlertDialog.Builder(
AlertDialogActivity.this).create();
// Setting Dialog Title
alertDialog.setTitle("Alert Dialog");
// Setting Dialog Message
alertDialog.setMessage("Welcome to AndroidHive.info");
// Setting Icon to Dialog
alertDialog.setIcon(R.drawable.tick);
// Setting OK Button
alertDialog.setButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// Write your code here to execute after dialog closed
Toast.makeText(getApplicationContext(), "You clicked on OK", Toast.LENGTH_SHORT).show();
}
});
// Showing Alert Message
alertDialog.show();
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With