以下问题:在显示项目列表时,我使用自定义arrayadapter并实现viewholder模式。我也使用convertviews。
加载时一切正常,列表项以正确的交替颜色显示。
但当我快速上下滚动时,颜色会改变,不再交替…
例如加载时:绿色、蓝色、绿色、蓝色…
卷轴后:绿色,蓝色,绿色,绿色,绿色,绿色…
下面是一些代码:
public View getView(int position, View convertView, ViewGroup parent) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder holder;
StoreTemplate curr = templates.get(position);
if (convertView == null) {
convertView = inflater.inflate(R.layout.template_store_rowlayout,
parent, false);
holder = new ViewHolder();
holder.name = (TextView) convertView
.findViewById(R.id.name);
// more attr skipped here...
}
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.name.setText(curr.getName());
// more attr set here...
// this changes background
if ((position % 2) == 0) {
convertView.setBackgroundColor(context.getResources().getColor(
R.color.background_green));
}
// code skipped here
return convertView;
}
我怎样才能保证,即使我滚动或搜索并重新加载列表,行也总是以不同的颜色显示?
最佳答案
您忘记了更改行背景的else
部分。你可能想这样做:
// this changes background
if ((position % 2) == 0) {
convertView.setBackgroundColor(context.getResources().getColor(
R.color.background_green));
} else {
convertView.setBackgroundColor(context.getResources().getColor(
R.color.your_color));
}