ListView备用行颜色在向上滚动和向下滚动时错误

问题描述:

以下问题:我使用自定义ArrayAdapter并在显示项目列表时实施ViewHolder模式。我也使用convertViews。 加载一切都很好,列表项目显示正确,交替的颜色。当我滚动快速上下,颜色变化,并不交替了... 例如当加载:绿色,蓝色,绿色,蓝色... 后滚动:绿色,蓝色,绿色,绿色,环保,绿色....ListView备用行颜色在向上滚动和向下滚动时错误

下面是一些代码:

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; 
} 

我怎么能保证,该行始终altenately着色,即使我滚动,或搜索并重新加载列表?

+1

我会把一个** else **分支给你的**甚至**行的颜色** ** **。 – 2014-09-01 19:02:46

你忘记if statementelse部分,你要更改行背景。你可能想这样尝试:

// 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)); 
    } 
+0

非常感谢。你节省了我的时间! – MOHRE 2016-07-31 09:28:35