我试图在自定义Listview中显示详细的产品信息,其中键/值对每行有两个TextView。数据显示正确。我每隔两行也涂上不同的颜色。

还有我的问题。如果我上下滚动,则不同颜色的行会更改其颜色并保持这种状态。数据不受此问题的影响。只是TextViews的背景色。我使用了ViewHolder模式,但这并没有改变任何东西。我添加了适配器的代码。我认为就足够了。你有什么主意吗

问题的屏幕截图:

java - Android-自定义ListView Viewholder-LMLPHP

码:

public class ProductDetailAdapter extends BaseAdapter {

private LinkedHashMap<String,String> list;
private Context context;

public ProductDetailAdapter(Context c, LinkedHashMap<String,String> list){
    super();
    this.context = c;
    this.list=list;

}
@Override
public int getCount() {
    return list.size();
}

@Override
public Object getItem(int position) {
    return list.get(position);
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup viewGroup) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    ProductDetailAdapter.ViewHolder viewHolder;

    if(convertView == null){
        convertView=inflater.inflate(R.layout.product_detail_data_row,null);
        viewHolder = new ViewHolder();
        viewHolder.textViewKey = (TextView) convertView.findViewById(R.id.productDataKey);
        viewHolder.textViewValue = (TextView) convertView.findViewById(R.id.productDataValue);
        convertView.setTag(viewHolder);

    }else {
        viewHolder = (ProductDetailAdapter.ViewHolder) convertView.getTag();
    }

    viewHolder.textViewKey.setText((String)list.keySet().toArray()[position]);
    viewHolder.textViewValue.setText(list.get(list.keySet().toArray()[position]));

    if(position % 2 == 0){
        viewHolder.textViewKey.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite2));
        viewHolder.textViewValue.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite2));
    }

    return convertView;
}

private static class ViewHolder {

    public TextView textViewKey;
    public TextView textViewValue;

    public ViewHolder(){};

}
}

最佳答案

发生这种情况是因为行被回收了。这是一个普遍的问题。

您可以通过以下方法解决此问题:

if(position % 2 == 0){
    viewHolder.textViewKey.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite2));
    viewHolder.textViewValue.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite2));
} else {
    viewHolder.textViewKey.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite1)); //Or the color that you want for odd rows
    viewHolder.textViewValue.setBackgroundColor(context.getResources().getColor(R.color.colorParkerWhite1)); //Or the color that you want for odd rows
}

10-04 11:42