2010-03-06 60 views
28

我是Android的新手,我想我正在嘗試做一些非常基本的事情:我的數組中有5個字符串(比如'One','Two',.. )。我想將這5個字符串添加到我的listactivity中的列表視圖中。Android:填充列表視圖與數組項目

我的列表:

<ListView 
    android:id="@+id/android:list" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content"/> 
</LinearLayout> 

我的列表行:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:orientation="horizontal"> 
<TextView android:id="@+id/homeItemName" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_weight="1"/> 
</LinearLayout> 

基本上,我要綁定的數組項的TextView的homeItemName。以後我可能會在我的行中添加其他項目,所以我不能將listview綁定到條目。

謝謝!

+1

您需要Adapters和ArrayAdapters的基本知識。 您可能需要擴展其中的一個類。 – daliz 2010-03-07 00:43:44

回答

31

對於代碼的例子,我們快速瀏覽一下這個step-by-step tutorial

setListAdapter(new ArrayAdapter<String>(this, R.layout.list_item, COUNTRIES)); 
ListView lv = getListView(); 

它顯示了一個ArrayAdapter的基本實現:

R.layout.list_item:是XML佈局(list_item.xml)將用於您的列表視圖的每個行。 COUNTRIES是字符串數組。

+1

鏈接死了:(。[是](https://developer.android.com/guide/topics/ui/layout/listview.html)你指出的那個? – 2016-05-17 09:18:13

6

您可以使用ArrayAdapter來綁定您的數據。由於您希望能夠向視圖添加額外的數據項,因此您需要給適配器ArrayList(因爲數組的大小是固定的)。應通過ArrayAdapter添加項目,您的ArrayList將自動更新。我在​​