Java 安卓:我能';t通过布局对象的id获取布局对象

Java 安卓:我能';t通过布局对象的id获取布局对象,java,android,xml,layout,Java,Android,Xml,Layout,这是xml代码: <?xml version="1.0" encoding="utf-8"?> <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" android:id="@+id/mainLayout" android:layout_width="fill_parent" android:layout_height="fill_parent" andr

这是xml代码:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/mainLayout"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">
</LinearLayout>
布局始终为空


为什么呢?id是正确的,可以毫无问题地获取所有其他元素。

您是否已使用以下代码将其附加到“活动”中

setContentView(R.layout.layout_id);
仅当视图当前通过应用程序的
setContentView(ID.OF.LAYOUT)
可见时,直接调用
findViewById()。否则,您必须自己膨胀视图。如果已经有一个视图对象,则可以按如下方式从中提取其他视图:

View v=alreadyInflatedView.findviewbyd(R.id.idOfChildView)

编辑:

如何膨胀视图:

LayoutInflater inflater =(LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View v = inflater.inflate(R.layout.idOfViewToInflate, null);

您需要从xml设置contentView

setContentView(R.layout.main); //this will put it on the screen.

必须首先膨胀/创建视图,以便findViewById()可以访问该视图。此视图是否可见(例如,显示在活动上)或您是否需要将其置于此上下文之外?不确定,但我认为您必须尝试干净地构建您的项目。谢谢!我不知道在获取视图之前必须调用setContentView。我的Android编程第二天:)
setContentView(R.layout.main); //this will put it on the screen.