2012-05-26 23 views
1

我原型的Android应用程序,并正尝试编写任何Java代码之前定义的UI。基本的XML布局的东西工作正常,但我无法弄清楚如何添加ListView与内容。在LinearLayout内添加ListView可以正常工作,但我无法添加任何内容(甚至没有其他LinearLayout)作为此ListView内容如何用布局XML中的内容定义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. 

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

奖金问题:有没有办法在build-time的XML布局中发现问题,而不是等待Android在运行时抛出异常?

回答

3

基本的XML布局工作正常,但我无法弄清楚如何添加一个ListView的内容。

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

奖金的问题:有没有办法在 集结时间来检测,而不是等待的Android在 运行时抛出一个异常,在XML布局问题,?

我猜的Android已经做到这一点。在ListView内容放置在XML布局(可能)OK,因为ListViewViewGroup,但后来当机器人实际上是尝试添加内容到ListView它会失败,因为这个例外称,由于操作不受支持。

+0

好的,知道了。感谢您的快速和彻底的答案! – kiwidrew