I would like to keep my dialog open when I press a button. At the moment it's closing.
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setMessage("Are you sure you want to exit?")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
MyActivity.this.finish();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
You can get the Dialog returned from method "show()" alertBuidler.
Call the "show()" method of "adb" and get Dialog
So you can call any button of your dialog at any point of code in your activity:
You will probably need to define your own layout and not use the "official" buttons; the behavior you're asking for is not typical of a dialog.
I believe the answer by @Kamen is correct, here is an example of the same approach using an anonymous class instead so it is all in one stream of code:
I wrote a more detailed write up to answer the same question here https://stackoverflow.com/a/15619098/579234 which also has examples for other dialogs like DialogFragment and DialogPreference.
Thanks Sogger for your answer, but there is one change that we have to do here that is, before creating dialog we should set possitive button (and negative button if there is need) to AlertDialog as traditional way, thats it.
Referenced By Sogger.
Here is the sample example ...
Yes, you can. You basically need to:
onClickListener
So, create a listener class:
Then when showing the dialog use:
Remember, you need to show the dialog otherwise the button will not be findable. Also, be sure to change DialogInterface.BUTTON_POSITIVE to whatever value you used to add the button. Also note that when adding the buttons in the DialogBuilder you will need to provide
onClickListeners
- you can not add the custom listener in there, though - the dialog will still dismiss if you do not override the listeners aftershow()
is called.You do not need to create a custom class. You can register a View.OnClickListener for the AlertDialog. This listener will not dismiss the AlertDialog. The trick here is that you need to register the listener after the dialog has been shown, but it can neatly be done inside an OnShowListener. You can use an accessory boolean variable to check if this has already been done so that it will only be done once: