I would like to display an ok cancel dialog to the user and I would like to know if use pressed ok, cancel, or if he chose to just dismiss the dialog by clicking elsewhere on the screen or pressing back button.
AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
final EditText input = new EditText(MainActivity.this);
builder.setView(input);
builder.setPositiveButton("OK", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// ok stuff
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// cancel stuff
}
});
builder.setOnDismissListener(new DialogInterface.OnDismissListener()
{
@Override
public void onDismiss(DialogInterface dialog)
{
//dismiss stuff
}
});
builder.show();
The problem here is that whenever user presses ok button, dismiss listener gets triggered right after.Is there any way to not trigger dismiss listener if user presses button?
I do realize that I can use a boolean flag, but I am hoping that there is actually an elegant solution.
I am not searching for solution on how to prevent dialog from being dismissed. I am searching for solution on how to prevent dismiss listener from being triggered when ok button is pressed and dialog gets dismissed.
setOnDismissListener() will be called for any reason. It means if dialog will disappear from the screen either due to Ok/Cancel button press or screen touch or back button or home button press, setOnDismissListener()
will be called.
Sets the callback that will be called when the dialog is dismissed for any reason.
If you are interested in listening for all cases where the dialog is dismissed and not just when it is canceled, see setOnDismissListener
So workaround it what you have mentioned, check using some boolean flags and handle it.