How do I fire an event when click occurs outside a dialog

烂漫一生 提交于 2019-11-26 16:13:18

问题


I would like to know how to solve a problem I've got.

I have a Dialog which pops up in an activity. The Dialog doesn't cover the whole screen, so the buttons from the activity still show. I can easily close the dialog when there is a touch outside the dialog's bounds with dialog.setCanceledOnTouchOutside(true);

However what I want to do is fire an event if a click is outside the Dialog's bounds (e.g if someone touches a button on the main Activity, it should close the Dialog and fire that event at the same time).


回答1:


It Works For me,,

        Window window = dialog.getWindow();
        window.setFlags(WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL,
                WindowManager.LayoutParams.FLAG_NOT_TOUCH_MODAL);
        window.clearFlags(WindowManager.LayoutParams.FLAG_DIM_BEHIND);

        dialog.show();

See this http://developer.android.com/reference/android/view/WindowManager.LayoutParams.html#FLAG_NOT_TOUCH_MODAL




回答2:


When dialog.setCanceledOnTouchOutside(true); then you just override onCancel() like this:

dialog.setOnCancelListener(
        new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                //When you touch outside of dialog bounds, 
                //the dialog gets canceled and this method executes.
            }
        }
);

Type your code inside the onCancel() method so it runs when the dialog gets canceled.




回答3:


If you are within custom dialog class, and wish to catch 'click outside' event - override cancel(). If you wish to catch 'dialog closed' event - override dismiss(). I recommend inserting logic BEFORE super.dismiss(). Kotlin example:

override fun dismiss() {
    Utils.hideKeyboard(mContext, window)
    super.dismiss()
}



回答4:


You can use an OnCancelListener to fire an event when a click occurs outside a dialog:

dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
    @Override
    public void onCancel(DialogInterface dialog) {
        yourFunction();
    }
});



回答5:


In DialogFragment you can use AlertDialog and the answer of @silverTech:

override fun onDismiss(dialog: DialogInterface) {
    yourMethod()
    super.onDismiss(dialog)
}

or

override fun onCancel(dialog: DialogInterface) {
    super.onCancel(dialog)
    yourMethod()
}


来源:https://stackoverflow.com/questions/9516287/how-do-i-fire-an-event-when-click-occurs-outside-a-dialog

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!