使用 ArrayList 填充 ListView? [英] Populating a ListView using an ArrayList?

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

问题描述

我的 Android 应用需要使用 ArrayList 中的数据填充 ListView.

My Android app needs to populate the ListView using the data from an ArrayList.

我无法做到这一点.有人可以帮我提供代码吗?

I have trouble doing this. Can someone please help me with the code?

推荐答案

您需要通过 ArrayAdapter 来实现,它会将您的 ArrayList(或任何其他集合)调整到您布局中的项目(ListView、Spinner 等).

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 开发者指南 是这样说的:

A ListAdapter 管理由任意对象数组支持的 ListView.默认情况下,此类期望提供的资源 ID 引用单个 TextView.如果要使用更复杂的布局,请使用也带有字段 id 的构造函数.该字段 id 应引用较大布局资源中的 TextView.

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.

然而,TextView 被引用,它将填充数组中每个对象的toString().您可以添加自定义对象的列表或数组.覆盖对象的 toString() 方法以确定将为列表中的项目显示什么文本.

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.

使用 TextViews 以外的东西来显示数组,例如 ImageViews,或者除了 toString() 结果之外还有一些数据填充视图,覆盖 getView(int, View, ViewGroup) 以返回您想要的视图类型.

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.

所以你的代码应该是这样的:

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天全站免登陆