调用 removeAllViews();仍然导致 IllegalStateException:You 必须先在 child 的 parent 上调用 removeView()

Calling removeAllViews(); still results in IllegalStateException:You must call removeView() on the child's parent first

我不确定为什么会这样,但我收到一条错误消息:调用 layout.removeAllViews(); 仍然会导致 IllegalStateException: The specified child already has a parent. 您必须在 child 上调用 removeView()先是parent.

奇怪的是我调用了:removeAllViews();在添加新的之前:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.download);

...

    ImageView imageViewz = (ImageView) findViewById(R.id.imageView6); 
            Picasso.with(context).load(background).into(imageViewz);

LinearLayout layout = new LinearLayout(Download.this);
                layout.setId(R.id.download);
                LayoutParams layoutParams 
                 = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
                layout.setLayoutParams(layoutParams);
                layout.setOrientation(LinearLayout.VERTICAL);
                LayoutParams imageViewLayoutParams 
                 = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
                imageViewz.setLayoutParams(imageViewLayoutParams);
                layout.removeAllViews();
                layout.addView(imageViewz);
                setContentView(layout);

但我仍然遇到致命错误...所以我不确定为什么会发生这种情况。

如有任何建议,我们将不胜感激。

您的问题不在于 layout。您的问题出在 imageViewz。它已经有一个父级,这就是触发您的异常的原因。在将其添加到 layout.

之前,您需要从其当前父项中删除 imageViewz