Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

AlertDialog dismiss not working

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?

like image 246
barq Avatar asked Feb 22 '16 12:02

barq


2 Answers

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();

like image 61
Strider Avatar answered Oct 05 '22 12:10

Strider


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();
like image 30
Vivek Mishra Avatar answered Oct 05 '22 11:10

Vivek Mishra