我的 main.xml
看起来像这样:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
既然根元素是一个LinearLayout
,它扩展了ViewGroup
,为什么main.xml
会变成一个View
而不是 ViewGroup
?例如,在我的主 Activity
类中,我尝试获取 LinearLayout
包含的 subview 数量,如下所示:
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ViewGroup vg = (ViewGroup) findViewById(R.layout.main);
Log.v("myTag", "num children: " + vg.getChildCount());
但是当我调用vg.getChildCount()
时它崩溃了。
正确的做法是什么?
最佳答案
findViewById
应该采用布局 XML 文件中定义的 View 的 ID,而不是文件本身的 ID。一旦您手动或通过 setContentView 膨胀了 View ,您就可以使用它来获取布局(如果您这样做的话):
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:id="@+id/mainlayout"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
作者:
ViewGroup vg = (ViewGroup) findViewById(R.id.mainlayout);
请注意 android:id
属性的添加以及在 findViewById
调用中使用匹配的 R.id
值。它的用法与 Dev Guide 中描述的相同。 。然后,您应该能够安全地将结果转换为 ViewGroup
或 LinearLayout
。
如果,在某些情况下,您想单独加载主视图,例如作为 subview ,使用 getLayoutInflater()
。 inflate(...)
构建并检索它。
关于java -/res/layout/main.xml描述的是一个View还是一个ViewGroup?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3340446/