将自定义对象添加到ArrayAdapter。如何抓取数据?

时间:2012-07-21 15:45:52

标签: android list object android-arrayadapter

这是我到目前为止所做的:

自定义对象:

class ItemObject {
    List<String> name;
    List<String> total;
    List<String> rating;

public ItemObject(List<ItemObject> io) {
    this.total = total;
    this.name = name;
    this.rating = rating;
 }
}

调用适配器:

List<String> names, ratings, totals;

ItemObject[] io= new ItemObject[3];
io[0] = new ItemObject(names);
io[1] = new ItemObject(rating);
io[2] = new ItemObject(totals);

adapter = new ItemAdapter(Items.this, io);
setListAdapter(adapter);

假设上面看起来没问题,我的问题是如何设置ItemAdapter,它是构造函数,并从对象中解开三个List。然后,在getView中,分配以下内容:

每个匹配位置:

    TextView t1 = (TextView) rowView.findViewById(R.id.itemName);
    TextView t2 = (TextView) rowView.findViewById(R.id.itemTotal);
    RatingBar r1 = (RatingBar) rowView.findViewById(R.id.ratingBarSmall);

例如,数组“名称”中的位置0为t1。 将数组“totals”中的0位置设置为t1。 将数组“rating”中的0置于r1。

编辑:我不希望有人编写整个适配器。我只需要知道如何从自定义对象中解包列表,以便我可以使用这些数据。 (甚至没有提出或在另一个问题中提出的问题

1 个答案:

答案 0 :(得分:11)

您的代码无法以其实际形式运行。您真的需要ItemObject中的数据列表吗?我的猜测是否定的,您只需要一个ItemObject,其中包含3个字符串,对应于行布局中的3个视图。如果是这种情况:

class ItemObject {
    String name;
    String total;
    String rating;// are you sure this isn't a float

public ItemObject(String total, String name, String rating) {
    this.total = total;
    this.name = name;
    this.rating = rating;
 }
}

然后,您的列表将合并到ItemObject

列表中
List<String> names, ratings, totals;
ItemObject[] io= new ItemObject[3];
// use a for loop
io[0] = new ItemObject(totals.get(0), names.get(0), ratings(0));
io[1] = new ItemObject(totals.get(1), names.get(1), ratings(1));
io[2] = new ItemObject(totals.get(2), names.get(2), ratings(2));
adapter = new ItemAdapter(Items.this, io);
setListAdapter(adapter);

适配器类:

public class ItemAdapter extends ArrayAdapter<ItemObject> {

        public ItemAdapter(Context context,
                ItemObject[] objects) {
            super(context, 0, objects);         
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // do the normal stuff
            ItemObject obj = getItem(position);
            // set the text obtained from obj
                    String name = obj.name; //etc       
                    // ...

        }       

}
相关问题