错误:指定的子级已经有父级 (Android)
问题:
频繁切换两种布局会导致以下错误:
FATAL EXCEPTION: main java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.
代码片段:
<code class="java">tv = new TextView(getApplicationContext()); // initialized elsewhere et = new EditText(getApplicationContext()); // initialized elsewhere 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); } }); }</code>
解决方案:
错误消息建议在将子级(TextView)添加到新布局之前将其从当前父级中删除。
在layout.addView(tv);之前添加以下代码;:
<code class="java">if (tv.getParent() != null) { ((ViewGroup) tv.getParent()).removeView(tv); // Fix }</code>
这可以确保 TextView 在添加到新布局之前从任何现有父级中正确删除,从而防止指定的父级冲突。
以上是为什么我在 Android 中收到“指定的子项已经有父项”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!