androiod:使用ImageView的Arraylist getview仅返回最后一个数据

时间:2015-10-20 02:50:43

标签: android listview arraylist imageview placeholder

ArrayList<Message> msg;
public View getView(int position, View convertView, ViewGroup parent) {
    Message message = (Message) this.getItem(position);
    Holder holder;
    if (convertView == null) {
        holder = new Holder();
        convertView = LayoutInflater.from(mContext).inflate(R.layout.activity_list, parent, false);
        holder.imageView = (ImageView) convertView.findViewById(R.id.img);
        convertView.setTag(holder);
    } else {
        holder = (Holder) convertView.getTag();
    }

    mAlphaSplit = new Character[message.getMessage().length()];
    for (int i = 0; i < message.getMessage().length(); i++) {
        mAlphaSplit[i] = new Character(message.getMessage().charAt(i));
        for (int j = 0; j < ALPHA.length; j++) {
            if (mAlphaSplit[i] == ALPHA[j]) {
                holder.imageView.setImageResource(ICONS[j]);
                break;
            }
        }
    }

    LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) holder.imageView.getLayoutParams();
    if (message.isMine()) {
        holder.imageView.setBackgroundResource(R.drawable.bubble_mine);
        lp.gravity = Gravity.RIGHT;
    } else {
        holder.imageView.setBackgroundResource(R.drawable.bubble_not_mine);
        lp.gravity = Gravity.LEFT;
    }
    holder.imageView.setLayoutParams(lp);
    return convertView;
}

这是我的getview方法。我想得到每个字母的相应图像,但我输入的东西后。最后一个相应的图像只是要返回的图像。

我的getCount

public int getCount() {
    return msg.size();
}

1 个答案:

答案 0 :(得分:0)

我认为问题在你的循环中。

    mAlphaSplit = new Character[message.getMessage().length()];
    for (int i = 0; i < message.getMessage().length(); i++) {
        mAlphaSplit[i] = new Character(message.getMessage().charAt(i));
        for (int j = 0; j < ALPHA.length; j++) {
            if (mAlphaSplit[i] == ALPHA[j]) {
                holder.imageView.setImageResource(ICONS[j]);
                break;
            }
        }
    }

现在,对于每个视图,您正在使用Alpha搜索mAlphaSplit中的所有字符。它与每个角色匹配,但每次获得匹配时,它都会设置imageview。因此,如果您在mAlphaSplit中有[&#39; A&#39; B&#39; C&#39;],那么首先它与A&#39;匹配,找到它,然后设置图像,然后再次找到匹配&#39; B&#39;然后&#39; C&#39;。所以C的图像设置为最后设置图像。我认为不需要外循环,而是使用如下的位置。

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

你的getCount

public int getCount() {
    if(message==null||message.getMessage()==null) return 0;
    return message.getMessage().size();
}