7

AlertDialog使用构建器创建了。它显示我们何时调用该show()方法。我在该对话框中有取消按钮。我可以通过单击取消按钮来取消该对话框。我的问题是一旦我取消显示对话框,我就无法再次显示对话框。它抛出一个异常,如:

09-09 12:25:06.441: ERROR/AndroidRuntime(2244): java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
09-09 12:25:06.441: ERROR/AndroidRuntime(2244):     at android.view.ViewGroup.addViewInner(ViewGroup.java:1970)
09-09 12:25:06.441: ERROR/AndroidRuntime(2244):     at android.view.ViewGroup.addView(ViewGroup.java:1865)
09-09 12:25:06.441: ERROR/AndroidRuntime(2244):     at android.view.ViewGroup.addView(ViewGroup.java:1845)
09-09 12:25:06.441: ERROR/AndroidRuntime(2244):     at com.android.internal.app.AlertController.setupView(AlertController.java:364)
09-09 12:25:06.441: ERROR/AndroidRuntime(2244):     at com.android.internal.app.AlertController.installContent(AlertController.java:205)
09-09 12:25:06.441: ERROR/AndroidRuntime(2244):     at android.app.AlertDialog.onCreate(AlertDialog.java:251)
4

4 回答 4

19

不要显示相同的对话框,创建一个新的。

发生这种情况是因为您试图重新使用已经创建(可能在onCreate)并使用过一次的对话框。重用对话框没有问题,但在问题中指定的子项(视图)已经有一个父项(对话框)。您可以通过删除父项继续,也可以创建一个新的父项,例如:-

alertDialog=new AlertDialog(Context);
alertDialog.setView(yourView);
alertDialog.show();
于 2010-09-09T08:37:26.873 回答
3

在添加新对话框之前删除上一个对话框。如果您每次都继续添加新对话框,这将留在您的记忆中,并且您的应用程序将消耗更多电池。

在要添加对话框的布局上调用删除视图或 removeAllViews()。

于 2011-03-15T06:38:24.567 回答
3

你必须这样做:

AlertDialog.setView(yourView);

您可以通过以下方式克服此错误:

if (yourView.getParent() == null) {
    AlertDialog.setView(yourView);
} else {
    yourView = null; //set it to null
    // now initialized yourView and its component again
    AlertDialog.setView(yourView);
}
于 2013-01-11T17:02:08.357 回答
1

将构建器的所有代码移到onCreateDialog方法之外。

例如,这里是更新的 Android Dialogs 指南:

AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage(R.string.dialog_fire_missiles)
    .setPositiveButton(R.string.fire, new DialogInterface.OnClickListener() {
         public void onClick(DialogInterface dialog, int id) {
             // Send the positive button event back to the host activity
             mListener.onDialogPositiveClick(NoticeDialogFragment.this);
         }
    })
    .setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            // Send the negative button event back to the host activity
            mListener.onDialogNegativeClick(NoticeDialogFragment.this);
        }
    });

final Dialog dialog = builder.create();

DialogFragment fragment = new DialogFragment {
    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        // Build the dialog and set up the button click handlers
        return dialog;
    }
};
fragment.show();

// and later ...
fragment.show();
于 2015-02-03T23:16:06.130 回答