Java Android:使用数组项填充列表视图

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/2394176/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 06:57:12  来源:igfitidea点击:

Android: Populating a listview with array items

javaandroidarrayslistview

提问by Prabhu

I'm new to Android and I think I'm trying to do something really basic: I have a 5 strings in my Array (say 'One', 'Two', ...). I want to add these 5 strings to my list view in my listactivity.

我是 Android 新手,我想我正在尝试做一些非常基本的事情:我的数组中有 5 个字符串(比如“一”、“二”……)。我想将这 5 个字符串添加到我的 listactivity 中的列表视图中。

My List:

我的列表:

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

My List Row:

我的列表行:

<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>

Basically, I want to bind the Array items to the TextView homeItemName. I might add other items in my row later, so I can't just bind the listview to the entries.

基本上,我想将 Array 项绑定到 TextView homeItemName。稍后我可能会在我的行中添加其他项目,所以我不能只是将列表视图绑定到条目。

Thanks!

谢谢!

采纳答案by Hubert

For code, take a quick look at this step-by-step tutorial

对于代码,请快速查看此分步教程

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

It shows a basic implementation of an ArrayAdapter:

它显示了 ArrayAdapter 的基本实现:

R.layout.list_item : is the xml layout (list_item.xml) that will be used for every ROW of your listview. COUNTRIES is the array of Strings.

R.layout.list_item :是将用于列表视图的每个 ROW 的 xml 布局 (list_item.xml)。COUNTRIES 是字符串数组。

回答by Klarth

You can use an ArrayAdapterto bind your data. Since you want to be able to add extra data items to the view, you to give the adapter an ArrayList(since an array is of a fixed size). Items should be added via the ArrayAdapterand your ArrayListwill be updated automatically. I have an example at http://www.box.net/shared/yduel9txya

您可以使用ArrayAdapter来绑定您的数据。由于您希望能够向视图添加额外的数据项,因此您需要为适配器提供一个ArrayList(因为数组的大小是固定的)。应通过ArrayAdapter添加项目,您的ArrayList将自动更新。我在http://www.box.net/shared/yduel9txya有一个例子