滚动之前适配器无法正常工作

时间:2015-10-30 21:06:18

标签: android listview android-adapter android-drawable android-viewholder

在我的Listview中,我希望TextViews的图像Drawables相应于文本。 我尝试使用下面的代码但是当文本按预期显示时,Drawable总是显示列表中所有TextView的最后一种颜色 - 直到滚动列表,然后它显示正确的颜色。

 @Override
public View getView(final int position, View convertView, ViewGroup parent) {
    ViewHolder holder;
    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    View row = convertView;
    if (row == null) {
        row = inflater.inflate(R.layout.mylayout, parent, false);
        holder = new ViewHolder();
        holder.textView = (TextView) row.findViewById(R.id.myTextView);
        holder.img = getResources().getDrawable(R.drawable.my_icon);
        row.setTag(holder);
    } else {
        holder = (ViewHolder) row.getTag();
    }

    holder.textView.setText(colors[position]);

    int color = 0;
    switch (colors[position])
    {
        case "blue":
            color = getResources().getColor(R.color.blue);
            break;
        case "green":
            color = getResources().getColor(R.color.green);
            break;
        case "red":
            color = getResources().getColor(R.color.red);
            break;
    }

    holder.img.setColorFilter(color, PorterDuff.Mode.SRC_ATOP);
    holder.textView.setCompoundDrawablesWithIntrinsicBounds(null, null, null, holder.img);
    return row;
}
static class ViewHolder {
    TextView textView;
    Drawable img;
}

1 个答案:

答案 0 :(得分:0)

why you are trying to point holder.img to a drawable image. you should use a view and setbackgroundcolour as it