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

主宰稳场 提交于 2019-12-12 00:27:00

问题


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:


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.



来源:https://stackoverflow.com/questions/31865059/calling-removeallviews-still-results-in-illegalstateexceptionyou-must-call-r

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!