最近android的listview写多了,也学习了各种listview的优化,列如viewHolder的使用。今天做item颜色设置时遇到一个新的问题。我这里设置“未完成”是灰色的,“已完成”是蓝色。我在item.xml设置所有字体都是灰色的,然后在viewholder设置颜色变化,当为“已完成”时设置为蓝色,这样的逻辑似乎一切正常,但当我测试时滑动listview,下面的“未完成”居然变成蓝色的!!!以下是Adapter的代码
public class ToneListAdapter extends ArrayAdapter<ToneList> {
private int resource;
public ToneListAdapter(Context context, int resource, List<ToneList> objects) {
super(context, resource, objects);
// TODO Auto-generated constructor stub
this.resource = resource;//resource为listView的每个子项的布局id
}
View view;
ViewHolder viewHolder;
if(convertView==null){
view = LayoutInflater.from(getContext()).inflate(resource, null);
viewHolder = new ViewHolder();
viewHolder.toneTitle =(TextView) view.findViewById(R.id.tv_tone_title);
viewHolder.toneTime =(TextView) view.findViewById(R.id.tv_tone_time);
viewHolder.toneFinish = (TextView) view.findViewById(R.id.tv_tone_finish);
viewHolder.toneBeginStudy = (ImageView) view.findViewById(R.id.img_tone_beginStudy);
viewHolder.toneLookResult = (ImageView) view.findViewById(R.id.img_tone_lookresult);
view.setTag(viewHolder);
}else {
view = convertView;
viewHolder = (ViewHolder) view.getTag();
}
final ToneList classList = getItem(position);//获得实例,final才能被onclick等内部类引用,position需要被引用也需要加final
if(classList!=null){
viewHolder.toneTitle.setText(classList.getTitle());
viewHolder.toneTime.setText(classList.getTime());
viewHolder.toneFinish.setText(classList.getFinish());
if(classList.getFinish().equals("已完成")){
//setTextColor(R.color.finish_blue)无效
viewHolder.toneFinish.setTextColor(getContext().getResources().getColor(R.color.finish_blue));//没作用?
}
//进入学习监听器
viewHolder.toneBeginStudy.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), classList.getTitle()+"begin study", Toast.LENGTH_SHORT).show();
}
});
//查看成绩监听器
viewHolder.toneLookResult.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(getContext(), classList.getTitle()+"LookResult", Toast.LENGTH_SHORT).show();
}
});
}
return view;
}
这是为什么?后来我查了listView滑动的机制才发现:listView被滑动时,移出视图的item会被缓存下来,下面的item会复用移出的item的样式!我的解决方法是:也设置未完成的颜色。这样每次getView就会重新设置一次。
if(classList.getFinish().equals("已完成")){
//setTextColor(R.color.finish_blue)无效
viewHolder.toneFinish.setTextColor(getContext().getResources().getColor(R.color.finish_blue));//没作用?
}
else{//一定要写else设置未完成,不然当滑动列表时,会有背景色错位
viewHolder.toneFinish.setTextColor(getContext().getResources().getColor(R.color.finish_No));
}