2012-10-19 52 views
1

我試圖複製,然後編輯在XML文件中定義的佈局視圖。複製LinearLayout視圖

//Create layout 
LinearLayout layout = new LinearLayout(this); 


//Add views 
layout = (LinearLayout)findViewById(R.id.layout1); 
//layout.addView(textView); 

setContentView(layout); 

這似乎是它應該工作,但我每次運行時,應用程序崩潰時,我打電話線 setContentView(layout);。 我已經雙重檢查了身份證,他們都很好,他們都是LinearLayouts。 任何想法發生了什麼問題?

+3

請張貼您的logcat錯誤堆棧跟蹤.. –

回答

2

很簡單,你不能在setContentView之前撥打findViewById,因爲沒有佈局設置來查找視圖!將會發生什麼情況是findViewById將返回null,然後您嘗試將內容設置爲layout(這是null),從而出現錯誤。

撥打setContentView,首先查看您的佈局資源ID或實際視圖,然後找到您的LinearLayoutfindViewById

+0

非常感謝,我完全錯過了。 – CmdrDoom