0

I want to handle the back press event when showing a popup window in android. I do like this. In the fragment:

@Override
public boolean onBackPressed() {
    if (backPressStrategy == BACK_PRESS_PLAN_A) {
        if (guideDialog != null) {
            guideDialog.dismiss();
        }
        closeFlashPay(REQ_CLOSE_FLASH_PAY_AND_FINISH);
        return true;
    } else if (backPressStrategy == BACK_PRESS_PLAN_B) {
        if (guideDialog != null) {
            guideDialog.dismiss();
        }
        getActivity().finish();
        return true;
    } else {
        return false;
    }
}

And in the Activity, I do like this

@Override
public void onBackPressed() {
     PayBaseFragment contentFragment = (PayBaseFragment) getSupportFragmentManager().findFragmentByTag(TAG_CONTENT_FRAGMENT);
     if (contentFragment != null && contentFragment.onBackPressed()) {
         return;
     }
     super.onBackPressed();
}

The problem is, the first time when I pressed back button, the popupwindow just disappeared and the override onBackPressed method was not invoked. Unless I press back button two times. I show my popup window like this

guideDialog.showAtLocation(getActivity().getWindow().getDecorView(), Gravity.CENTER, 0, 0);

Thanks for help

Akeshwar Jha
  • 4,516
  • 8
  • 52
  • 91
Zijian
  • 207
  • 1
  • 9
  • I think the dialog is consuming the back press as cancel. Look at this http://stackoverflow.com/questions/10346011/how-to-handle-back-button-with-in-the-dialog – X3Btel Jun 27 '16 at 10:43
  • I saw this link, the problem is that I set the popupwindow forcursable. Should set it false – Zijian Jun 28 '16 at 09:31
  • Im not 100% sure what you expect to happen. Set onKey listener in the dialog and call closeFlashPay method there – X3Btel Jun 28 '16 at 13:02

1 Answers1

1

You need to handle the back button key of your dialog with this :

dialog.setOnKeyListener(new Dialog.OnKeyListener() {
                        @Override
                        public boolean onKey(DialogInterface arg0, int keyCode,
                                             KeyEvent event) {
                            if (keyCode == KeyEvent.KEYCODE_BACK) {
                                dialog.dismiss();
                                // you can call your onBackPress here

                            } 
                            return true;
                        }
                    });
Vodet
  • 1,491
  • 1
  • 18
  • 36