Calling removeAllViews(); still results in Illegal

2019-09-11 01:42发布

I'm not sure why this is happening but I'm getting an error stating: Calling layout.removeAllViews(); still results in IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

The strange part is I've called: removeAllViews(); before adding a new one:

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

Yet I still get the fatal error...so I'm not sure exactly why this is happening.

Any suggestions are appreciated.

1条回答
冷血范
2楼-- · 2019-09-11 02:25

Your problem is not with layout. Your problem is with imageViewz. It already has a parent, and that is what is triggering your exception. You need to remove imageViewz from its current parent before you add it to layout.

查看更多
登录 后发表回答