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 an
Solution 1:
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);
returntrue;
}
returnfalse;
}
})
//(Rest of the .stuff ...)
For answer in Kotlin see here:Not working onbackpressed when setcancelable of alertdialog is false
Solution 2:
Found a shorter solution :) try this:
accountDialog = builder.create();
accountDialog.setOnCancelListener(newOnCancelListener() {
@OverridepublicvoidonCancel(DialogInterface dialog) {
dialog.dismiss();
activity.finish();
}
});
Solution 3:
This handles both the BACK button and the click OUTSIDE the dialog:
yourBuilder.setOnCancelListener(newOnCancelListener() {
@OverridepublicvoidonCancel(DialogInterface dialog) {
dialog.cancel();
// do your stuff...
}
});
dialog.cancel()
is the key: with dialog.dismiss()
this would handle only the click outside of the dialog, as answered above.
Solution 4:
I created a new function within the java class and made a call to that function from the onClick method of the dialog Builder.
publicclassFilenameextendsActivity(){
@OverrideonCreate(){
//your stuff//some button click launches Alertdialog
}
publicvoidmyCustomDialog(){
AlertDialog.Builder alertDialogBuilder = newAlertDialog.Builder(this);
//other details for builder
alertDialogBuilder.setNegativeButton("BACK",
newDialogInterface.OnClickListener() {
@OverridepublicvoidonClick(DialogInterface dialog, int which) {
dialod.dismiss;
myCustomBack();
}
});
AlertDialog alertDialog = alertDialogBuilder.create();
alertDialog.setCanceledOnTouchOutside(true);
alertDialog.show();
}
publicvoidmyCustomBack(){
if(condition1){
super.onBackPressed();
}
if(condition 2){
//do stuff here
}
}
@OverridepublicvoidonBackPressed(){
//handle case hereif (condition A)
//Do thiselse//Do that
}
}
Post a Comment for "Android: How To Override Onbackpressed() In Alertdialog?"