Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Dismiss non-cancelable dialog on fragment backPress - Android

I have a Navigation drawer activity and many fragments that I reach via the nav drawer.

In some of these fragments, I show a dialog which says "Loading.." while background tasks are happening.

Now I've made my dialogs not-cancellable by dialog.setCancelable(false) so that the user doesn't accidentally dismiss it by clicking anywhere on the screen. This makes it un-cancelable even when the phone back button is pressed.

This is the code for my dialog -

Dialog dialog = new Dialog(context);
    dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
    dialog.setContentView(R.layout.custom_progress_dialog);
    ((TextView)dialog.findViewById(R.id.custom_dialog_message)).setText("Loading ...");

    dialog.setCancelable(false);     
    dialog.show();

I need to write code to dismiss the loading dialog and go to the previous fragment when the phone back button is pressed while on any fragment.

Can somebody help me out? Mostly I need implementing backPress specific to a fragment. Thanks!

like image 903
Mallika Khullar Avatar asked Sep 30 '15 10:09

Mallika Khullar


1 Answers

It's simple as this

dialog.setOnKeyListener(new Dialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface dialog, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                dialog.dismiss();
            }
            return true;
        }
    });
like image 81
NaviRamyle Avatar answered Oct 04 '22 14:10

NaviRamyle