Android Call AlertDialog onBackPressed

I am trying to finish my main menu in my application. I thought it would be just a nice touch to add an AlertDialog in the OnBackPressed method. However, for some reason, I get all kinds of errors.

I created an AlertDialog in OnBackPressed and show it, but the application just closes when I click 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 could not find anyone else with this problem.

+7
source share
3 answers

Try not to call super.OnBackPressed () , this shoul help 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) { MyActivity.this.finish(); } }) .setNegativeButton("No", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { dialog.cancel(); } }); AlertDialog alert = builder.create(); alert.show(); } 
+30
source

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 added a new public onSuperBackPressed method using the super method in MyActivity.

Thanks for K_Anas for a great idea.

+3
source

I created an AlertDialog in OnBackPressed and show it, but the application just closes when I click the back button and I get errors saying that the window is leaking.

If you call super.OnBackPressed() inside your OnBackPressed , then the application will end up, as the basic OnBackPressed implementation OnBackPressed . Do not call the super method and the application will not be closed.

+2
source

All Articles