Christine Ramos Christine Ramos - 11 months ago 102
Android Question

How to close or cancel custom alert dialog

I tried closing the

when cancel button is clicked, but it is not working. I tried using
but none of them works.

Here's the snippet of my code:

final AlertDialog.Builder alertDialog = new AlertDialog.Builder(context);
LayoutInflater layoutInflater = LayoutInflater.from(context);
final View viewer = layoutInflater.inflate(R.layout.input_dialog, null);

alertDialog.setTitle("Edit Albums Name");

Button send =(Button) viewer.findViewById(;
Button cancel =(Button) viewer.findViewById(;

final AlertDialog dialog = alertDialog.create();

cancel.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
dialog.cancel(); // dialog.dismiss();

Answer Source

The problem is a simple, but tricky one: You create a AlertDialog from the builder and call it dialog. When the cancel button is clicked, you close the dialog. But you have never actually shown the dialog, i.e. called, but instead called the show() method of the Builder which is called alertDialog. That method creates and shows the dialog in one step, but it creates a new instance, which you don't give a name to, and thus can't close anymore.

You either need to call instead of or use AlertDialog dialog = and remove the second completely.