我试图做这个愚蠢的“游戏”,我有一个相对布局和从View扩展的类。我创建了视图,并希望使用Thread将它们添加到Relative布局中。到现在为止还挺好。我让它工作得很好,小对象视图向下滚动相对布局。然后我添加了两个选项屏幕,只有在那些屏幕后我才想用滚动视图显示Activity。问题是它停止处理以下错误:
08-03 20:13:48.140:E / AndroidRuntime(5152):java.lang.IllegalStateException:指定的子节点已经有父节点。您必须首先在孩子的父母身上调用removeView()。
我无法理解这个错误...
以下是启动的线程的示例代码和更新UI的函数:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
context = this.getApplicationContext();
/*load all bitmaps*/
loadBitmaps();
/*get all the activities components*/
gameCanvasRL = (RelativeLayout)findViewById(R.id.gameCanvasRL);
playerScoreTV = (TextView)findViewById(R.id.playerPoints);
/*GameManager instance*/
manager = GameManager.getInstance();
/*Start Threads*/
startAllThreads();
}
private void startAllThreads() {
refreshCanvasHandler = new Handler();
spawnHandler = new Handler();
refreshCanvasThread = new Thread(new RefreshCanvasTask());
spawnTask = new Thread(new spawnTask());
refreshCanvasThread.start();
spawnTask.start();
}
class RefreshCanvasTask implements Runnable {
@Override
public void run() {
while(true) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
refreshCanvasHandler.post(new Runnable() {
@Override
public void run() {
refreshCanvas();
}
});
}
}
}
private void refreshCanvas(){ int germSize;
/*Move all germs*/
manager.moveGerms();
germSize = manager.getGerms().size();
if(gameCanvasRL.getChildCount() > 0)
gameCanvasRL.removeAllViews();
for(int i = 0; i < germSize; i++) {
gameCanvasRL.addView(manager.getGerms().get(i));
}
}
答案 0 :(得分:0)
错误意味着您正在尝试添加已添加到另一个视图的视图。视图可能只有1个父项,因此第二个添加会引发异常。在将其添加到新父级之前,您需要将其从原始父级中删除。