2012-05-26 21 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