onCreateDialog()中的AlertDialog.Builder无法正常工作

时间:2015-02-08 16:28:49

标签: android dialog

我正在使用ViewPager(v4)与DialogFragment实施对话框。除非我尝试将标题,正面按钮和负面按钮添加到对话框中,否则一切正常。

这就是我的所作所为:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
    AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
    builder.setTitle("修改时间...")
    .setPositiveButton(R.string.dialog_setDatetime_positiveButton, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {

        }
    })
    .setNegativeButton(R.string.dialog_setDatetime_negativeButton, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialogInterface, int i) {
            getDialog().dismiss();
        }
    });
    AlertDialog dialog = builder.show();
    return dialog;
}

(只是忽略中文字符,因为我认为它们没有任何差异。)

结果是,标题和按钮未显示。似乎AlertDialog.Builder无法正常工作或我做错了什么?

在运行Lollipop的Nexus 5上测试过。

编辑:如果我调用builder.create()并返回对话框,我将收到错误消息:

android.util.AndroidRuntimeException: requestFeature() must be called before adding content

3 个答案:

答案 0 :(得分:0)

您需要调用builder.create()然后返回对话框。

答案 1 :(得分:0)

您可以像下面一样使用它。(只需忽略中文字符)

void exit() {

    Dialog noticeDialog;
    AlertDialog.Builder builder = new Builder(this);

    builder.setMessage("确定退出? ");
    builder.setPositiveButton("退出", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            AppManager.getAppManager().AppExit(SettingActivity.this);
        }
    });
    builder.setNegativeButton("取消", new OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            dialog.dismiss();
        }
    });
    noticeDialog = builder.create();
    noticeDialog.show();
}

答案 2 :(得分:0)

以下适用于我:

@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {

    return new AlertDialog.Builder(getActivity())
            .setTitle("title")
            .setPositiveButton("Positive button",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            //process the positive button click event
                        }
                    }
            )
            .setNegativeButton("Negative button",
                    new DialogInterface.OnClickListener() {
                        public void onClick(DialogInterface dialog, int whichButton) {
                            //process the negative button click event
                        }
                    }
            )
            .create();
}