动态构建 类 并将它们添加到 ArrayAdapter

Dynamically Build Classes and add them to an ArrayAdapter

我有一个填充数据列表 "neededRepData",我正在尝试将此列表添加到我的适配器中,但遇到了问题。下面是我的 Reps class 和我的方法(来自另一个 class)来遍历 neededRepData。

public class Reps {
    public int icon;
    public String title;

    public Reps() {
        super();
    }

    public Reps(int icon, String title) {
        super();
        this.icon = icon;
        this.title = title;
    }
}

List<Reps> listOfReps = new ArrayList<Reps>();
    for (int i = 0; i < neededRepData.size(); i++) {
        String currentRep = neededRepData.get(i);
        listOfReps.add(new Reps(R.drawable.unknown_representative, currentRep));
    }    

此时我的 listOfReps 中包含了我所期望的一切。但是,当我创建我的适配器时,我被迫执行如下操作。

Reps customRepData[] = new Reps[]{
                       new Reps(listOfReps.get(0).icon, listOfReps.get(0).title)
    };

LocalRepAdapter adapter = new LocalRepAdapter(this, R.layout.mylist, customRepData);    

我想将我动态创建的 customRepData[] 对象传递到我的适配器中,我看不到在 customRepData[] 的构造中循环的方法,也许有更好的方法?

我的扩展 ArrayAdapter class 看起来像这样:

public class LocalRepAdapter extends ArrayAdapter<Reps> {

Context context;
int layoutResourceId;
Reps data[] = null;

public LocalRepAdapter(Context context, int layoutResourceId, Reps[] data) {
    super(context, layoutResourceId, data);
    this.layoutResourceId = layoutResourceId;
    this.context = context;
    this.data = data;
}    ......

谢谢。

您被迫创建 类 Reps customRepData[] 的数组,因为您的适配器的构造函数采用 类 的数组,但您可以轻松地将其更改为

public LocalRepAdapter(Context context, int layoutResourceId, ArrayList<Reps> list)

所以您不再需要 Reps customRepData[],您可以像

一样将 listOfReps 传递给它
LocalRepAdapter adapter = new LocalRepAdapter(this, R.layout.mylist, listOfReps);