Material-dialogs: Catch onBackPressed() while showing MaterialStyledDialogs

Created on 28 Jun 2016  路  5Comments  路  Source: afollestad/material-dialogs

Hi,
I set a MaterialStyledDialogs with the parameter setCancelable(false).

I can't dismiss the dialog without first set some parameters that the user can choose inside the dialog, because they are mandatory for the app. Anyway, I want to give the user the chance to close the app and come back later, if he/she doesn't want to make the choices at the moment.

I thought that a way would be to catch the pressing of the phone back button while the dialog is open and write the logic to close the app.

Is it possible to catch the back button pressing?

questiodiscussion

Most helpful comment

@bejibx You can handle onBackPressed when dialog is open like this...

dialog.setOnKeyListener(new Dialog.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface arg0, int keyCode,
                                 KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    Log.i("back key pressed", "Back key pressed");
                    if (condition)
                        dialog.dismiss();
                }
                return true;
            }
});

dialog.show();

All 5 comments

You can only catch onBackPressed from the Activity, or an sub-class of Dialog.

Otherwise I believe you can set a key event listener to the dialog.

@afollestad I think you are not quite right about it. There is a Dialog#onBackPressed() method which you can use to catch back button press. BackButtonCallback could be really usefull.

@bejibx You can handle onBackPressed when dialog is open like this...

dialog.setOnKeyListener(new Dialog.OnKeyListener() {
            @Override
            public boolean onKey(DialogInterface arg0, int keyCode,
                                 KeyEvent event) {
                if (keyCode == KeyEvent.KEYCODE_BACK) {
                    Log.i("back key pressed", "Back key pressed");
                    if (condition)
                        dialog.dismiss();
                }
                return true;
            }
});

dialog.show();

@bmbariah multi-line syntax highlighting is a bit different than how you formatted your comment ;) updated

Was this page helpful?
0 / 5 - 0 ratings