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

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

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

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


当前回答

你只需要传递attachtorroot参数false。

mBinding = FragmentCategoryBinding.inflate(inflater, container, false)

其他回答

你只需要传递attachtorroot参数false。

mBinding = FragmentCategoryBinding.inflate(inflater, container, false)

这就是我如何做我的自定义对话框

AlertDialog.Builder builder = new AlertDialog.Builder(MainActivity.this);
android.view.View views = getLayoutInflater().inflate(layout_file, null, false);

builder.setView(views);
dialog = builder.create();
dialog.show();

我把它改成了这个,它对我有用,我希望这对我有帮助

Dialog dialog = new Dialog(MainActivity.this);
dialog.setContentView(layout_file);
dialog.show();

在KOTLIN中简化

 viewToRemove?.apply {
            if (parent != null) {
                (parent as ViewGroup).removeView(this)
            }
        }

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

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

它不见了:

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

如果其他解决方案不奏效,比如:

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

检查你从片段的onCreateView返回了什么它是单个视图还是视图组?在我的情况下,我在碎片的xml根上有viewpager,我正在返回viewpager,当我在布局中添加viewgroup时,我没有更新,我现在必须返回viewgroup,而不是viewpager(view)。