在对话框外单击时,dialog.setCanceledOnTouchOutside(true)不起作用

时间:2017-12-04 13:06:18

标签: java android alertdialog android-alertdialog

我使用DialogFragment创建/显示dialog

此外,当我在对话框外点击时,我想忽略对话。

我在创建对话后尝试调用dialog.setCanceledOnTouchOutside(true)方法,但它无效。

我尝试了其他帖子中的一些解决方案,但仍无效。

问题出在哪里?

这是我的代码DialogSelectCategory.java

<!-- language: java -->
public class DialogSelectCategory extends DialogFragment {
    static final String tag = "DialogSelectCategory";
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        Activity act = getActivity();
        AlertDialog.Builder builder = new AlertDialog.Builder(act);
        String title = getResources().getString(R.string.select_category);
        View view = LayoutInflater.from(act).inflate(R.layout.dialog_category, null, false);
        builder.setView(view);
        builder.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {
                dialog.dismiss();
            }
        });
        builder.setOnCancelListener(new DialogInterface.OnCancelListener() {
            @Override
            public void onCancel(DialogInterface dialog) {
                dialog.dismiss();
            }
        });

        Dialog dialog = builder.create();
        setCancelable(true);
        dialog.setCanceledOnTouchOutside(true);

        return dialog;
    }

    public void showDialog(FragmentManager fragmentManager) {
        FragmentTransaction ft = fragmentManager.beginTransaction();
        Fragment prev = fragmentManager.findFragmentByTag(tag);
        if (prev != null) {
            ft.remove(prev);
        }
        ft.addToBackStack(null);
        this.show(fragmentManager, tag);
    }
}  

1 个答案:

答案 0 :(得分:0)

使用DialogFragment显示Dialog

时出现问题

根据http://developer.android.com/reference/android/app/DialogFragment.html,解决方案是在DialogFragment中覆盖onCancel

// DialogFragment, not Dialog
@Override
public void onCancel(DialogInterface dialog) {
}