指定的孩子已经有父母

时间:2010-09-09 06:58:35

标签: android alertdialog

我使用构建器创建了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 个答案:

答案 0 :(得分:17)

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

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

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

答案 1 :(得分:3)

在添加新对话框之前删除上一个对话框。如果您每次继续添加新对话框,它将保留在您的内存中,您的应用程序将消耗更多电量。

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

答案 2 :(得分: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);
}

答案 3 :(得分:1)

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

例如,这里更新了Android对话框指南:

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();
相关问题