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

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

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

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


当前回答

在我的例子中,我将id命名为约束布局的“root”,这与现有的父根id冲突。

试着改变id。

<androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/root"  //<--It should not named as root.
            android:layout_width="match_parent"
            android:layout_height="match_parent"

</androidx.constraintlayout.widget.ConstraintLayout>

其他回答

if(tv!= null){
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}

我的错误是这样定义视图:

view = inflater.inflate(R.layout.qr_fragment, container);

它不见了:

view = inflater.inflate(R.layout.qr_fragment, container, false);

检查是否已经添加了视图

if (textView.getParent() == null)
    layout.addView(textView);

当我试图使用attach to root将一个片段提交到true而不是false时,我得到了这个消息,就像这样:

return inflater.inflate(R.layout.fragment_profile, container, true)

后做的事情:

return inflater.inflate(R.layout.fragment_profile, container, false)

它工作。

在我的例子中,我将id命名为约束布局的“root”,这与现有的父根id冲突。

试着改变id。

<androidx.constraintlayout.widget.ConstraintLayout
            android:id="@+id/root"  //<--It should not named as root.
            android:layout_width="match_parent"
            android:layout_height="match_parent"

</androidx.constraintlayout.widget.ConstraintLayout>