ArrayAdapter.getView returns 仅获取最后一项

ArrayAdapter.getView returns only the last item being fetch

这是我的 getview 代码。它总是 returns 最后一个被提取的项目。我该如何解决这个问题。我是 HolderView 的新手。 *更新代码

public static final char[] ALPHA = {'a', 'b'....};
int[] ICONS = {R.drawable.a, R.drawable.b....};
public CustomList(Context context, Character[] split) {
    super(context, R.layout.activity_list, split);
    inflater = LayoutInflater.from(context);
    this.alphaSplit = split;
}
static class Holder {
    ImageView imageView;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
    Holder holder;
    if (convertView == null) {
        convertView = inflater.inflate(R.layout.activity_list, parent, false);
        holder = new Holder();
        holder.imageView = (ImageView)convertView.findViewById(R.id.img);
        convertView.setTag(holder);
    } else {
        holder = (Holder)convertView.getTag();
    }

    setImage:
    for (int loop = 0; loop < alphaSplit.length; loop++) {
        for (int j = 0; j < ALPHA.length; j++) {
            if (alphaSplit[loop] == ALPHA[j]) {
                holder.imageView.setImageResource(ICONS[j]);
                break setImage;
            }
        }
    }
    return convertView;
}

我只是想得到每个字母对应的图像。这就是为什么我有一个嵌套循环,因为从那里,我可以获得图标的位置。 外循环是用户输入的文本,我将其解析为一个字符(因为如果我要使用字符,它会出错)。并且内部循环是 ALPHA 的字符 = {'a', 'b'.. until 'z' and '0' to '9'}

在方法 getView 中,循环应该像这样匹配时中断:

for (int loop = 0; loop < alphaSplit.length; loop++) {
    for (int j = 0; j < ALPHA.length; j++) {
        if (alphaSplit[loop] == ALPHA[j]) {
            holder.imageView.setImageResource(ICONS[j]);
            break; //ATTENTION PLS!!!
        }
    }
}

顺便说一句,您不需要在 getView 中调用 notifyDataSetChangedFYI

PS:也许你需要像这样打破两个循环:

outer:
for (int loop = 0; loop < alphaSplit.length; loop++) {
    for (int j = 0; j < ALPHA.length; j++) {
        if (alphaSplit[loop] == ALPHA[j]) {
            holder.imageView.setImageResource(ICONS[j]);
            break outer; //ATTENTION PLS!!!
        }
    }
}

更新:

更改代码:

 setImage:
for (int loop = 0; loop < alphaSplit.length; loop++) {
    for (int j = 0; j < ALPHA.length; j++) {
        if (alphaSplit[loop] == ALPHA[j]) {
            holder.imageView.setImageResource(ICONS[j]);
            break setImage;
        }
    }
}

像这样:

for (int j = 0; j < ALPHA.length; j++) {
   if (alphaSplit[position] == ALPHA[j]) {
        holder.imageView.setImageResource(ICONS[j]);
        break;
    }
}

并覆盖 getCount 方法:

@Override
public int getCount() {
    return this.alphaSlipt.length;
}