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

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

问题描述

我的的Andr​​oid 应用程序需要填充的ListView 使用从的ArrayList <数据/ code>。

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

我有麻烦这样做。是否有人可以帮助我的code?

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开发者指南说:

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,查看,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.

所以你的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天全站免登陆