为什么AlertDialog.dialog.show()会第二次崩溃?

时间:2013-04-30 19:22:20

标签: android android-alertdialog showdialog

我的Android应用程序显示AlertDialog,第一次一切正常。但是,在显示然后取消Dialog后,它第二次在show()上崩溃。我试过在类似帖子中提出的建议,但没有任何帮助。这是我的代码:

    addButton.setOnClickListener(this);
}

@Override
public void onClick (View view) {
    switch (view.getId()) {
    case R.id.config_add: 
        builder = new AlertDialog.Builder(this);
        builder.setTitle(R.string.create_content_server_config_title);
        builder.setView(config_view);
        builder.setPositiveButton(R.string.dialog_confirm_create_config_button, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User clicked Create button
                Toast.makeText(ManageContentServers.this, config_name.getText().toString(), Toast.LENGTH_LONG).show();
            }
        });
        builder.setNegativeButton(R.string.dialog_config_cancel_button, new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int id) {
                // User cancelled the dialog
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
        break;
    }
}

2 个答案:

答案 0 :(得分:0)

因为你正在使用“setView”。您需要每次都重新创建对话框!

 private void showDialog() { 
    builder = new AlertDialog.Builder(this); builder.setTitle(R.string.create_content_server_config_title); builder.setView(config_view);  builder.setPositiveButton(R.string.dialog_confirm_create_config_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User clicked Create button
                        Toast.makeText(ManageContentServers.this, config_name.getText().toString(), Toast.LENGTH_LONG).show();
                    }
                });
                builder.setNegativeButton(R.string.dialog_config_cancel_button, new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {
                        // User cancelled the dialog
                        dialog.dismiss();
                    }
                    });
                    dialog = builder.create();
                    dialog.show(); 
        }


    case R.id.config_add:
    showDialog();
    break;

答案 1 :(得分:0)

我不确定你是否说同样的话,但我通过移动更容易解决问题

config_view = inflater.inflate(R.layout.ecs_config_fields, null);

从onCreate()方法到onClick(),就在builder.setView(config_view)之前;