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

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

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

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


当前回答

下面的代码为我解决了这个问题:

@Override
public void onDestroyView() {
    if (getView() != null) {
        ViewGroup parent = (ViewGroup) getView().getParent();
        parent.removeAllViews();
    }
    super.onDestroyView();
}

注意:这个错误来自我的片段类,通过重写onDestroy方法,我可以解决它。

其他回答

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

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

当我为活动和片段使用数据绑定时,它发生在我身上。

对于fragment - in onCreateView,我们可以用传统的方式使用膨胀器来膨胀布局。 在onViewCreated方法中,绑定对象可以更新为

 binding = DataBindingUtil.getBinding<FragmentReceiverBinding>(view) as FragmentReceiverBinding

它解决了我的问题

你只需要传递attachtorroot参数false。

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

我的问题与许多其他答案有关,但需要做出改变的原因略有不同……我试图将一个活动转换为一个片段。所以我把膨胀代码从onCreate移动到onCreateView,但我忘记从setContentView转换到膨胀方法,同样的IllegalStateException把我带到了这个页面。

我改了这个:

binding = DataBindingUtil.setContentView(requireActivity(), R.layout.my_fragment)

:

binding = DataBindingUtil.inflate(inflater, R.layout.my_fragment, container, false)

这就解决了问题。

我找到了另一个解决办法:

if (mView.getParent() == null) {
                    myDialog = new Dialog(MainActivity.this);
                    myDialog.setContentView(mView);
                    createAlgorithmDialog();
                } else {
                    createAlgorithmDialog();
                }

在这里,我只是有一个if语句检查视图是否有一个父,如果它没有创建新的对话框,设置contentView并在我的“createAlgorithmDialog()”方法中显示对话框。

这也设置了积极和消极按钮(确定和取消按钮)与onClickListeners。