我必须经常在两种布局之间切换。下面发布的布局中发生了错误。
当我的布局第一次被调用时,没有发生任何错误,一切都很好。当我调用不同的布局(空白布局)并随后再次调用我的布局时,它会抛出以下错误:
> 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);
}
}
}
我知道这个问题之前已经被问过,但它对我的情况没有帮助。
最佳答案
错误消息说明了您应该做什么。
// TEXTVIEW
if(tv.getParent() != null) {
((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}
layout.addView(tv); // <========== ERROR IN THIS LINE DURING 2ND RUN
// EDITTEXT
关于java - 指定的子项已经有父项。您必须首先在子级的父级上调用removeView() (Android),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60599427/