1

我正在制作一个 Android 应用程序的原型,并尝试在编写任何 Java 代码之前定义 UI。基本的 XML 布局工作正常,但我不知道如何添加ListView内容。添加ListView里面 aLinearLayout工作正常,但我不能添加任何东西(甚至不是另一个LinearLayout)作为this的内容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>

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

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

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

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

4

2 回答 2

3

基本的 XML 布局工作正常,但我不知道如何添加带有内容的 ListView。

你不能。您最好的选择是使用具有指向数组资源ListView的属性的元素(这将显示一个简单的它应该是模拟行而不是单独的内容的东西)。android:entriesListViewStringsListViewScrollViewListViewListView

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

我猜android已经这样做了。ListView在 xml 布局中将内容放在 a中是可以的(可能),因为ListViewa 是 a ViewGroup,但后来当 android 实际尝试将内容添加到时,ListView它会失败,正如异常所说,因为该操作不受支持。

于 2012-05-26T07:52:37.537 回答
1

您并没有真正将其他视图“添加到”列表视图中,因为它不是一种可以添加嵌套布局和视图的布局。

请参阅本教程,因为它展示了如何正确填充和操作您的列表视图

http://developer.android.com/resources/tutorials/views/hello-listview.html

于 2012-05-26T08:00:37.840 回答