填充使用ArrayList的一个ListView? [英] Populating a ListView using ArrayList?

查看:215
本文介绍了填充使用ArrayList的一个ListView?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的安卓应用程序需要填充列表视图使用从数据数组列表。我有麻烦这样做。是否有人可以帮助我的code?

My Android app needs to populate the List-view using the data from an Array-list. I have trouble doing this. Can someone please help me with the code?

推荐答案

您需要通过做一个 ArrayAdapter 这会适应你的ArrayList(或任何其他集合)到在布局的项目(ListView控件,微调等)。

You need to do it through an ArrayAdapter which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).

这是什么 Android开发者指南说:

这是管理一个ListView一个ListAdapter   通过任意数组支持   对象。默认情况下此类预期   所提供的资源ID   引用单个的TextView。如果你   要使用更复杂的布局,使用   在构造函数,也可以带   ID字段。那场ID应   引用一个TextView在较大   布局资源。然而,TextView的   是引用,则将充满   在每个对象的的toString()   数组。您可以添加列表或数组   自定义对象。重写   你的对象的toString()方法来   确定文本将显示   对于在列表中的项目。要使用   比TextViews的一些其他   阵列的显示,例如,   ImageViews,或有一些数据的   除了的toString()结果填补   意见,覆盖getView(廉政,查看,   的ViewGroup)返回的视图的类型   你想要的。

A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource. However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list. To use something other than TextViews for the array display, for instance, ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

所以,你的code应该是这样的:

So your code should look like:

public class YourActivity extends Activity {

    private ListView lv;

    public void onCreate(Bundle saveInstanceState) {
         setContentView(R.layout.your_layout);

         lv = (ListView) findViewById(R.id.your_list_view_id);

         // Instanciating an array list (you don't need to do this, 
         // you already have yours).
         List<String> your_array_list = new ArrayList<String>();
         your_array_list.add("foo");
         your_array_list.add("bar");

         // This is the array adapter, it takes the context of the activity as a 
         // first parameter, the type of list view as a second parameter and your 
         // array as a third parameter.
         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                 this, 
                 android.R.layout.simple_list_item_1,
                 your_array_list );

         lv.setAdapter(arrayAdapter); 
    }
}

这篇关于填充使用ArrayList的一个ListView?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆