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将自动更新。我在​​