指定的子元素已经有一个父级。

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)

1
展示你调用AlertDialog的代码。 - LordTwaroog
又被称为绑架。 - cherrysoft
4个回答

19

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

这是因为您正在尝试重用已经创建并使用过一次的对话框(可能在onCreate中)。重复使用对话框没有问题,但是如问题所述,指定的子项(视图)已经有了父级(对话框)。您可以通过删除已有的父级或者创建一个新的父级来解决:

alertDialog=new AlertDialog(Context);
alertDialog.setView(yourView);
alertDialog.show();

7
这应该是一条评论! - swiftBoy

3

在添加新对话框之前,请删除先前的对话框。如果每次添加新对话框,这些对话框会一直留在内存中,因此您的应用程序将消耗更多电池电量。

在您添加对话框的布局上调用removeView或removeAllViews()。


也许现在对于当前的Android版本来说不再相关。 - AZ_

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);
}

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();

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接