setOnCancelListener and setOnDismissListener is not called for AlertDialog for back button pressed or touch outside

前端 未结 5 1649
佛祖请我去吃肉
佛祖请我去吃肉 2020-12-02 21:48

When

  • Touch outside the dialog region
  • Press on back button

I\'m expecting onDismiss (Or onCancel) will be call

相关标签:
5条回答
  • 2020-12-02 22:23

    you should read this topic: How to dismiss the dialog with click on outside of the dialog?

    Dialog dialog = new Dialog(context)
    dialog.setCanceledOnTouchOutside(true);
    
    0 讨论(0)
  • 2020-12-02 22:36

    in your DialogFragment, override

    @Override
    public void onStop() {
        super.onStop();
        if (mListener != null) {
           // do something here
        }
    }
    
    0 讨论(0)
  • 2020-12-02 22:40

    If you are using AlertDialog, see

    builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
        @Override
        public void onCancel(DialogInterface dialog) {
            // dialog dismiss without button press
        }
    });
    

    and dialog.setCanceledOnTouchOutside(true) (thanks @LeosLiterak)

    0 讨论(0)
  • 2020-12-02 22:45

    The problem happens when you are using DialogFragment to display Dialog

    According to http://developer.android.com/reference/android/app/DialogFragment.html, the solution is to override onCancel in DialogFragment

    Please take note from http://developer.android.com/reference/android/app/DialogFragment.html#onCreateDialog(android.os.Bundle) too

    Note: DialogFragment own the Dialog.setOnCancelListener and Dialog.setOnDismissListener callbacks. You must not set them yourself. To find out about these events, override onCancel(DialogInterface) and onDismiss(DialogInterface).

    // This is DialogFragment, not Dialog
    @Override
    public void onCancel(DialogInterface dialog) {
    }
    
    0 讨论(0)
  • 2020-12-02 22:45

    You have not set backPressed key event

    dialog.setOnKeyListener(new Dialog.OnKeyListener() {
        @Override
        public boolean onKey(DialogInterface arg0, int keyCode, KeyEvent event) {
            // TODO Auto-generated method stub
            if (keyCode == KeyEvent.KEYCODE_BACK) {
                finish();
            }
            return true;
        }
    });
    
    0 讨论(0)
提交回复
热议问题