Zijian
Zijian

Reputation: 227

The override method onBackPressed doesn't work when showing popup window

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

Upvotes: 0

Views: 359

Answers (1)

Vodet
Vodet

Reputation: 1519

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;
                        }
                    });

Upvotes: 1

Related Questions