Arrayadapter custom id



我有一个从baseadapter扩展而来的arrayadapter,并将其与存储数据的arraylist一起使用。我需要更新个别项目。所以在添加到arraylist时,我需要为每个项目提供一个id。然后我会用set方法更新它,如下所示:

randomsList.set(position,new Random(user,1));

我的意思是我需要一个职位价值。有人说您需要为此执行map。但我不知道该怎么做。我需要一个榜样。

这是我的课:

private static class Randoms{
    private List<Random> randoms=null;
    public Randoms(List<Random> randoms) {
        this.randoms=randoms;
    }
    public Random get(int position) {
        return randoms.get(position);
    }
    public int size() {
        return randoms.size();
    }
}

这是我的适配器:

private static class RandomsAdapter extends BaseAdapter{
    private Randoms randoms;
    private LayoutInflater inflater;
    private Context context;
    private RandomsAdapter(Context context,Randoms randoms) {
        this.randoms=randoms;
        this.inflater = LayoutInflater.from(context);
        this.context=context;
    }
    public void updateRandoms(Randoms randoms) {
        this.randoms=randoms;
        notifyDataSetChanged();
    }
    @Override
    public int getCount() {
        return randoms.size();
    }
    @Override
    public Random getItem(int position) {
        return randoms.get(position);
    }
    @Override
    public long getItemId(int position) {
        return 0;
    }
    public View getView(int position,View convertView,ViewGroup parent) {
    }
}

如果我理解正确,您希望使用项目在列表中的位置作为项目的id值:

您可以为Random创建一个包装类,它将包含Random对象及其id。

class RandomWrapper {
    private Random rand;
    private int id;
    RandomWrapper(Random rand, int id) {
        this.rand = rand;
        this.id = id;
    }
    public Random getRand() {
        return this.rand;
    }
    public int getID() {
        return this.id;
    }
}

这样,如果您想访问Random,请致电yourRandomWrapper.getRand();如果您想获得id,请致电yourRandomWrapper.getID()

因此,例如,将5项添加到您的列表中:

for(int i = 0; i < 5; i++) {
    randomsList.add(new RandomWrapper(yourRandomObj, i));
}

如果要为对象生成唯一的ID,可以使用java.util.UUID类。如果你对它的工作原理感兴趣,你可以查看这个答案或Oracle Docs

最新更新