I am trying to finish up my main menu in my application. I thought it would be a simple nice touch to add an AlertDialog in the OnBackPressed method. However for some reason I am getting all kinds of errors.
I created the AlertDialog in the OnBackPressed and show it but the app just closes when I press the back button and I get errors saying that the window is leaking.
Any idea how to fix this? I searched for about 30 minutes and couldn't find anyone else with this problem.
Try to not call super.OnBackPressed(), this code shoul help:
@Override
public void onBackPressed() {
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();
alert.show();
}
If you want to call super.onBackPressed() use this code:
@Override
public void onBackPressed() {
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) {
//finish();
MyActivity.this.onSuperBackPressed();
//super.onBackPressed();
}
})
.setNegativeButton("No", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
/*
if (handleCancel()){
super.onBackPressed();
}
*/
}
public void onSuperBackPressed(){
super.onBackPressed();
}
I just added a new public method onSuperBackPressed
with the super
-method to MyActivity.
Thanks goes to K_Anas for providing the excellent idea.
I created the AlertDialog in the OnBackPressed and show it but the app just closes when I press the back button and I get errors saying that the window is leaking.
If inside your OnBackPressed
you are calling super.OnBackPressed()
then the application will finish, as that's what the base implementation of OnBackPressed
does. Don't call the super
method, and the application won't close.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With