2011-03-17 74 views
0

我想提出一個佈局內的另一個佈局,但我這樣做時,它relLayout.addView(squareLayout);如何將佈局放入另一個佈局?

for (int i = 0; i < 6; i++) { 
    for (int j = 0; j < 7; j++) { 

     RelativeLayout relLayout = (RelativeLayout) findViewById(relIds[i][j]); 
     relLayout.removeAllViews(); 

     RelativeLayout squareLayout = (RelativeLayout) findViewById(R.id.square); 
     relLayout.addView(squareLayout); 
    } 
} 

請告訴我,我應該怎麼辦給出NullPointerException

+1

我們需要你的XML文件。另外,這是什麼「relIds」?你應該使用LogCat來找出哪兩個佈局是空的。 – Klaus 2011-03-17 12:09:22

+0

,因爲它聲明它在'relLayout.addView(squareLayout)'上給出'NullPointerException';'squareLayout應該爲null。你有沒有設置setContentView,是你的主佈局的「方形」視圖部分? – pankajagarwal 2011-03-17 13:48:30

回答

1

relLayout在訪問removeAllViews()方法時不爲空。所以無論是findViewById()還是另一個線程都會將null設置爲relLayout實例。

+0

爲什麼它應該是6?如果你說它是6,那麼可能會有'ArrayIndexOutOfBoundsException'而不是'NullPointerException'。編輯你的答案,並使其正確,然後我會退出投票。 – 2011-03-17 12:42:56

+0

@vikas:你說得對... – 2011-03-18 07:33:59

+0

這是個好人。我很欣賞這一點。 – 2011-03-18 07:42:51

0

使用不當relIds [] []沒有初始化可能也造成空指針異常

相關問題