android - 如何在布局 XML 中定义包含内容的 ListView?

标签 android android-layout android-xml

我正在制作一个 Android 应用程序的原型(prototype),并试图在编写任何 Java 代码之前定义 UI。基本的 XML 布局工作正常,但我不知道如何添加包含内容的 ListView。在 LinearLayout 中添加 ListView 效果很好,但我无法添加任何内容(甚至不能添加另一个 LinearLayout)作为 contents 这个 ListView

我尝试了一种相当明显的方法:

<ListView android:layout_width="fill_parent"
          android:layout_height="fill_parent"
          android:layout_weight="2">
    <LinearLayout android:orientation="vertical"
                  android:layout_width="fill_parent"
                  android:layout_height="fill_parent">
        <TextView android:text="Line One"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content" />
        <TextView android:text="Line Two"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content" />
        <TextView android:text="Line Three"
                  android:layout_width="wrap_content"
                  android:layout_height="wrap_content" />
    </LinearLayout>
</ListView>

但在尝试启动 Activity 时失败(在运行时)并出现异常:

java.lang.UnsupportedOperationException: addView(View, LayoutParams) is not supported in AdapterView.

XML 布局语言的 SDK 文档相当少,我似乎找不到任何明显的方法来完成这项工作。我错过了什么?

额外的问题:有没有办法在构建时检测 XML 布局中的问题,而不是等待 Android 在运行时抛出异常?

最佳答案

The basic XML layout stuff works fine, but I can't figure out how to add a ListView with contents.

你不能。您最好的选择是使用 ListView 元素和指向数组资源的 android:entries 属性(这将显示一个简单的 ListView Strings) 或通过将其替换为 ScrollView 来模拟 ListView,然后在 ListView 中添加您想要的内容> 作为 ListView 的内容(但它应该模拟行而不是单独的内容)。

Bonus question: is there a way to detect problems in the XML layout at build-time, instead of waiting for Android to throw an exception at runtime?

我想 android 已经做到了。将内容放在 ListView 中在 xml 布局中是可以的(可能)因为 ListView 是一个 ViewGroup,但稍后当 android 实际尝试添加时ListView 的内容将失败,如异常所述,因为该操作不受支持。

关于android - 如何在布局 XML 中定义包含内容的 ListView?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10764498/

相关文章:

Android Gradle 主项目和子模块风格

android - 将数据从 Activity 发送到另一个 Activity 而不启动它

android - 错误膨胀类 it.gmariotti.cardslib.library.view.CardListView

java - 尝试使用 Intent 登录时出现错误

android - OCR 与 Android 应用程序

java - 找不到模块 '<unknown>' 的 JDK 'appcompatV7'

Android - 从图库应用程序获取图像?

java - "Binary XML file line #8: You must supply a layout_width attribute"虽然属性已经存在

android - 重新格式化时如何使XML代码中的命名空间attr出现在下一行

android - View 中额外 8dp 边距背后的原因?不是解决方法