【问题标题】:Calling removeAllViews(); still results in IllegalStateException:You must call removeView() on the child's parent first调用 removeAllViews();仍然导致 IllegalStateException:You must call removeView() on the child's parent first
【发布时间】:2015-08-06 20:20:27
【问题描述】:

我不确定为什么会发生这种情况,但我收到一条错误消息:调用 layout.removeAllViews(); 仍会导致 IllegalStateException: The specified child already has a parent. 您必须先在孩子的父母上调用 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);

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

感谢任何建议。

【问题讨论】:

  • 请发布您的整个堆栈跟踪。我猜你的问题不在于layout,而在于imageViewz
  • 谢谢@CommonsWare - 如果这对你来说足够详细,请告诉我 - pastebin.com/4uWdz7Zq(顺便说一句,第 154 行是 layout.addView(imageViewz);)

标签: java android android-linearlayout fatal-error illegalstateexception


【解决方案1】:

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

【讨论】:

  • 我非常感谢@CommonsWare 的洞察力。我按照您的建议进行了尝试-但是我仍然在同一行上遇到相同的错误....我尝试了 3 种实现-似乎都没有工作-介意看一下吗? pastebin.com/fhEMG2Ug
  • @NoobDev910:您正试图从layout 中删除imageViewz。您刚刚在几行前创建了layout。你知道layout 不是imageViewz 的当前父级。
  • 知道了。 (感谢您的帮助)只是出于好奇......这不应该解决这个问题吗? layout.removeAllViews();布局.addView(imageViewz);设置内容视图(布局); (它仍然在同一点崩溃)
  • @NoobDev910:“这不应该解决这个问题吗?” - 不。 imageViewz 有一个父母。 那个父对象不是layout,因为你刚刚创建了layout 对象。因此,在layout 上调用removeAllViews()imageViewz 没有影响。 是把imageViewz放在另一位父母的人。 是必须确定父母是谁的人(例如,在imageViewz上致电getParent())。而 you 是必须让 那个父母(我再说一遍,这不是你新创建的 layout)从其列表中删除 imageViewz 的人孩子们。
猜你喜欢
  • 1970-01-01
  • 2023-03-11
  • 1970-01-01
  • 1970-01-01
  • 2022-12-28
  • 1970-01-01
  • 1970-01-01
  • 2019-04-13
  • 2021-01-22
相关资源
最近更新 更多