2012-03-22 158 views
0

我想通過它的ID調用LinearLayout。當我試圖這樣做時,我得到NoSuchFieldErrorAndroid線性佈局錯誤

LinearLayout l1 = (LinearLayout)findViewById(R.id.content2); 
setContentView(l1); 
+3

findViewById()用於獲取l1_after_,您已經從XML資源設置了內容視圖。這個示例代碼沒有意義... – Izkata 2012-03-22 18:53:48

回答

1

您所使用的方法是不正確的。

setContentView(R.layout.main)必須爲您的情況設置任何佈局,如main.xml。

現在主佈局的LinearLayout的ID爲content2。

此外,如果你想使用setContentView直接創建一個動態線性佈局,即不在xml中。

Linearlayout l1 = new LinearLayout(this); 
//Set Layout params and bla bla... as per your need.. 
now setContentView(l1); 
0

如果且僅當您在xml資源文件中給出該id並且正在膨脹,纔可以找到該id。如果不加載xml資源文件,您將無法找到該id。 YOu可以使用Activity onCreate()中的setContentView(R.layout.main);加載xml資源文件。查找id的代碼將類似於LinearLayout l = findViewById(R.id.content);