2017-03-02 77 views
0

我正嘗試在自定義列表視圖中顯示詳細的產品信息,每行有兩個TextViews用於鍵/值對。數據顯示正確。我也爲每一條第二條線着色不同。Android - 自定義ListView查看者

還有我的問題。如果我上下滾動,不同顏色的行會改變它們的顏色並保持這種狀態。數據不受此問題影響。只是TextViews的背景顏色。我使用ViewHolder模式,但這並沒有改變任何東西。我添加了適配器的代碼。我覺得那夠了。你有什麼想法嗎?

截圖的問題:

enter image description here

代碼:

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(){}; 

} 
} 
+0

工作圖片網址是壞了。請編輯你的問題。謝謝! – aldakur

+1

image url:https://i.stack.imgur.com/OS3Op.png對我來說很好用 – Mike

+0

嘗試在if(位置%2 == 0)內創建新的'ViewHolder instance'' – aldakur

回答

4

這是因爲行正在被回收。這是一個常見問題。一旦你通過數據源適配器你

super(); 

NO:

您可以通過執行解決它:

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

試試這個:

super(c, 0, list); 

,而不是這個更長的需求:

getCount將

的getItem

getItemId