Android线性布局错误

问题描述:

我想通过它的ID调用LinearLayout。当我试图这样做时,我得到NoSuchFieldErrorAndroid线性布局错误

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

findViewById()用于获取l1_after_,您已经从XML资源设置了内容视图。这个示例代码没有意义... – Izkata 2012-03-22 18:53:48

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

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); 

如果且仅当您在xml资源文件中给出该id并且正在膨胀,才可以找到该id。如果不加载xml资源文件,您将无法找到该id。 YOu可以使用Activity onCreate()中的setContentView(R.layout.main);加载xml资源文件。查找id的代码将类似于LinearLayout l = findViewById(R.id.content);