Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android: How to override onBackPressed() in AlertDialog?

I have an AlertDialog dlgDetails which is shown from another AlertDialog dlgMenu. I would like to be able to show dlgMenu again if the user presses the back button in dlgDetails and simply exit the dialog if he presses outside the dialog.

I think the best way to do this is to override onBackPressed for dlgDetails, but I am not sure how to do that since AlertDialogs must be created indirectly using the Builder.

I am trying to create a derived AlertDialog (public class AlertDialogDetails extends AlertDialog { ...} ) but then I guess I must also extend AlertDialog.Builder in that class to return an AlertDialogDetails, but isn't there a simpler way? And if not, how would you go about overriding the Builder?

like image 405
Pooks Avatar asked Oct 18 '11 03:10

Pooks


2 Answers

I finally added a key listener to my dialog to listen to the Back key. Not as elegant as overriding onBackPressed() but it works. Here is the code:

dlgDetails = new AlertDialog.Builder(this)     .setOnKeyListener(new DialogInterface.OnKeyListener() {         @Override         public boolean onKey (DialogInterface dialog, int keyCode, KeyEvent event) {             if (keyCode == KeyEvent.KEYCODE_BACK &&                  event.getAction() == KeyEvent.ACTION_UP &&                  !event.isCanceled()) {                 dialog.cancel();                 showDialog(DIALOG_MENU);                 return true;             }             return false;         }     })     //(Rest of the .stuff ...) 

For answer in Kotlin see here:Not working onbackpressed when setcancelable of alertdialog is false

like image 68
Pooks Avatar answered Sep 21 '22 20:09

Pooks


Found a shorter solution :) try this:

         accountDialog = builder.create();          accountDialog.setOnCancelListener(new OnCancelListener() {              @Override             public void onCancel(DialogInterface dialog) {                 dialog.dismiss();                 activity.finish();              }         }); 
like image 36
Lettings Mall Avatar answered Sep 20 '22 20:09

Lettings Mall