Reputation: 221
I tried closing the AlertDialog
when cancel button is clicked, but it is not working. I tried using .dismiss()
and .cancel()
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");
alertDialog.setView(viewer);
Button send =(Button) viewer.findViewById(R.id.saveAlBtn);
Button cancel =(Button) viewer.findViewById(R.id.dismissBtn);
final AlertDialog dialog = alertDialog.create();
cancel.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
dialog.cancel(); // dialog.dismiss();
}
});
alertDialog.show();
Upvotes: 1
Views: 1281
Reputation: 1746
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 dialog.show()
, 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 dialog.show()
instead of alertDialog.show()
or use AlertDialog dialog = alertDialog.show()
and remove the second alertDialog.show()
completely.
Upvotes: 4