在对话框外面按下时如何关闭DialogFragment?

sol*_*ole 75 android fragment dismiss

我正在使用a DialogFragment,虽然我已成功设置图像以在关闭时关闭(即关闭)对话框,但当用户点击对话框外的任何地方时,我很难找到解除对话框的方法,就像它一样正常的对话.我以为会有某种

dialogFragment.setCanceledOnTouchOutside(true);
Run Code Online (Sandbox Code Playgroud)

打电话,但我没有在文档中看到.

这有可能DialogFragment吗?或者我在错误的地方寻找?我尝试拦截"父母"活动中的触摸事件,但除了没有得到任何触摸事件外,它对我来说似乎不对.

小智 165

DialogFragment.getDialog().setCanceledOnTouchOutside(true);
Run Code Online (Sandbox Code Playgroud)

必须被召入onCreateView(正如Apurv Gupta指出的那样).

  • 必须在`onCreateView`中调用 (33认同)

man*_*ang 56

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
       ...
       getDialog().setCanceledOnTouchOutside(true);
       ... 
       }
Run Code Online (Sandbox Code Playgroud)


Yak*_*pan 20

    /** The system calls this only when creating the layout in a dialog. */
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // The only reason you might override this method when using onCreateView() is
        // to modify any dialog characteristics. For example, the dialog includes a
        // title by default, but your custom layout might not need it. So here you can
        // remove the dialog title, but you must call the superclass to get the Dialog.
        Dialog dialog = super.onCreateDialog(savedInstanceState);
        dialog.requestWindowFeature(Window.FEATURE_NO_TITLE);
        dialog.setCanceledOnTouchOutside(true);

        return dialog;
    }
Run Code Online (Sandbox Code Playgroud)


sud*_*007 6

这里有很多答案,但是,对话框打开时应用程序崩溃。getDialog().setCanceledOnTouchOutside(true);内部写入onCreateView无法正常工作并使我的应用程序崩溃。

(我正在AppCompatActivity用作我的BaseActivity和android.app.DialogFragment我的片段)。

起作用的是以下两行之一:

getDialog()。setCanceledOnTouchOutside(true);

要么

this.getDialog()。setCanceledOnTouchOutside(true);

里面onActivityCreated

@Override
    public void onActivityCreated(Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        //getDialog().getWindow().getAttributes().windowAnimations = R.style.DialogAnimationZoom;
        //getDialog().getWindow().setDimAmount(0.85f);
        getDialog().setCanceledOnTouchOutside(true);//See here is the code
    }
Run Code Online (Sandbox Code Playgroud)

不使用什么:

DialogFragment.getDialog()。setCanceledOnTouchOutside(false);

引发以下错误

在此处输入图片说明

而编写代码onCreateView会使应用程序崩溃!如果发现错误,请更新答案。


Tho*_*mas 6

如果您想在单击 a 外部时执行某些逻辑DialogFragment,只需重写 onCancel 方法即可。

override fun onCancel(dialog: DialogInterface) {
    super.onCancel(dialog)
    // Do your work here
}
Run Code Online (Sandbox Code Playgroud)