java - 调用removeAllViews();仍然导致 IllegalStateException :You must call removeView() on the child's parent first

标签 java android android-linearlayout fatal-error illegalstateexception

我不确定为什么会发生这种情况,但我收到一条错误消息:调用 layout.removeAllViews(); 仍然会导致 IllegalStateException: 指定的子项已经有父项. 您必须首先在子级的父级上调用removeView()。

奇怪的部分是我调用了: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);

但是我仍然遇到 fatal error ...所以我不确定为什么会发生这种情况。

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

最佳答案

您的问题不在于布局。您的问题出在 imageViewz 上。它已经有一个父级,这就是触发您的异常的原因。在将 imageViewz 添加到 layout 之前,您需要从其当前父级中删除它。

关于java - 调用removeAllViews();仍然导致 IllegalStateException :You must call removeView() on the child's parent first,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31865059/

相关文章:

android - android webView 中的异常

java - 如何找到 Spring beans.xml

java - 如何定义可以通过单击访问的 Javadoc 链接

java - Java 中 HTTP 响应的返回值

android - 如何扩展 AdapterView 使其表现得像由适配器动态填充的 LinearLayout

java - 如何从 LinearLayout 中删除 View 而不影响其他 subview 的位置?

java - Android:当我还在 View 上设置 layoutParams 时,在 View 上调用 setPadding() 不起作用

java - 如何在不将代理添加到我的 git 存储库的情况下在 Heroku Play Framework 中安装 New Relic?

java - OrmLite 多对多的扭曲

android - 无法让MediaRecorder以高采样率进行录制