指定的子项已有父项。您必须先在孩子的父母上调用 removeView() (Android)

新手上路,请多包涵

我必须经常在两种布局之间切换。错误发生在下面发布的布局中。

当我的布局第一次被调用时,没有发生任何错误,一切都很好。当我调用另一个布局(一个空白布局)然后第二次调用我的布局时,它会抛出以下错误:

 > FATAL EXCEPTION: main
>     java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

我的布局代码如下所示:

     tv = new TextView(getApplicationContext()); // are initialized somewhere else
    et = new EditText(getApplicationContext()); // in the code

private void ConsoleWindow(){
        runOnUiThread(new Runnable(){

     @Override
     public void run(){

        // MY LAYOUT:
        setContentView(R.layout.activity_console);
        // LINEAR LAYOUT
        LinearLayout layout=new LinearLayout(getApplicationContext());
        layout.setOrientation(LinearLayout.VERTICAL);
        setContentView(layout);

        // TEXTVIEW
        layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
        // EDITTEXT
        et.setHint("Enter Command");
        layout.addView(et);
        }
    }
}

我知道之前有人问过这个问题,但对我的情况没有帮助。

原文由 blackst0ne 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 426
2 个回答

错误消息说明您应该做什么。

 // TEXTVIEW
if(tv.getParent() != null) {
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
layout.addView(tv); //  <==========  ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT

原文由 Zielony 发布,翻译遵循 CC BY-SA 4.0 许可协议

简单地传递参数

attachtoroot = 假

View view = inflater.inflate(R.layout.child_layout_to_merge, parent_layout, false);

原文由 Akshay Sahai 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题