java -/res/layout/main.xml描述的是一个View还是一个ViewGroup?

标签 java android layout view

我的 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 中描述的相同。 。然后,您应该能够安全地将结果转换为 ViewGroupLinearLayout

如果,在某些情况下,您想单独加载主视图,例如作为 subview ,使用 getLayoutInflater()inflate(...)构建并检索它。

关于java -/res/layout/main.xml描述的是一个View还是一个ViewGroup?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3340446/

相关文章:

java - 如何检测一个点是否与 libgdx 中的主体相交

java.io.IOException : Cannot run program adb. exe CreateProcess 错误=5,访问被拒绝

java - java中的对象和引用

android - Android 9 上的生物识别管理器

java - 如何在android中使用 Volley 发送参数数组

android - 位图在 ImageView 上居中时出现问题

java - 如何使用 volley 在 android 中上传视频

html - CSS Div 以及附带的 Span

silverlight - 如何使 ContentControl 水平拉伸(stretch)

java - 使用Picasso从firebase获取图像问题