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?
Try this
Declare your
AlertDialog
at the top like:than replace your
dialogBuilder.show();
withthan u can call
myAlertDialog.dismiss();
try this ... it worked for me ... You can use this method for your dialog or you can simply use alert.dismiss(); to dismiss the dialog .... or just put the dialog method in your code and call the method i.e. MyAlertDialogBox(); wherever you want a dialog box .
Trying below code while using
interface
to create your own dialog button click listener.MyOnClickListener.java
Your dialog Code:
Output:
Open your dialog:
Performing OnClick of dialog:
I hope its helps you.
When you change the line
dialogBuilder.show()
todialogBuilder.create().show()
it should be working correctly.Instead of
dialog.dismiss()
, usedialoginterface.dismiss()
.I've shown an example below