Android Prompting an AlertDialog onBackPressed
android, android-alertdialog
Solution
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();
}
Problem
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.