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

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

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

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


当前回答

我也犯了同样的错误,看看我做了什么。我的坏,我试图将相同的视图NativeAdView添加到多个FrameLayouts,通过为每个FrameLayout创建一个单独的视图NativeAdView来解决,谢谢

其他回答

如果你正在使用MaterialAlertDialog,这对我来说是有效的:

(yourChildView.parent as? ViewGroup)?.removeView(yourChildView)

错误消息告诉您应该做什么。

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

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

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

它不见了:

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

就我而言,我做错了:

...
TextView content = new TextView(context);
for (Quote quote : favQuotes) {
  content.setText(quote.content);
...

代替(好):

...
for (Quote quote : favQuotes) {
  TextView content = new TextView(context);
  content.setText(quote.content);
...

如果你正在使用ViewBinding,请确保你引用了正确的绑定!

当我试图从一个活动中膨胀一个自定义对话框时,我有这个问题:

AlertDialog.Builder builder = new AlertDialog.Builder(this);

final AlertBinding alertBinding = AlertBinding.inflate(LayoutInflater.from(this), null, false);

builder.setView(binding.getRoot()); // <--- I was using binding (which is my Activity's binding), instead of alertBinding.