2016-10-05 54 views
0

我已經做了一個適配器到我的ListView,我想以編程方式更改一些行的顏色,如果他們有我指定的值。ListView滾動時丟失格式

下面的代碼顯示了這是如何實現的。兩件奇怪的事情發生:

1)第一行應該畫,但不是;

2)其他行(除了第一行)色彩鮮豔,但執行滾動時會丟失背景色。

public View getView (int position, View convertView, ViewGroup parent) { 
     convertView = (RelativeLayout) inflater.inflate(resource, null); 
     Content Legend = getItem(position); 

     TextView name = (TextView) convertView.findViewById(R.id.name); 
     name.setText(Legend.getName()); 

     TextView value = (TextView) convertView.findViewById(R.id.value); 

     if (Legend.getValue().equals("Color")){ 
      convertView.setBackgroundColor(Color.GRAY); 
      Legend.setValue(""); 
     }*/ 
     value.setText(Legend.getValue()); 

     return convertView; 
    } 

回答

0

listView中的視圖將被重用,試着認爲你在一個地方設置了每個視圖。所以,你需要考慮所有情況,添加其他{}

if (Legend.getValue().equals("Color")){ 
     convertView.setBackgroundColor(Color.GRAY); 
     Legend.setValue(""); 
    } else { 
    //set background and other value if not equals "color" 

}

0
static class ViewHolderItem { 
    TextView name, value; 
public ViewHolderItem(View view) { 
      name = (TextView) view.findViewById(R.id.name); 
value = (TextView) view.findViewById(R.id.value); 
} 


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

     ViewHolderItem holder; 
     if (convertView == null) { 
      convertView = inflater.inflate(R.layout.xxx, parent, false); 
      holder = new MyHolder(convertView); 
      convertView.setTag(holder); 
     } else { 
      holder = (MyHolder) convertView.getTag(); 
     } 
      Content Legend = getItem(position); 
      holder.name.setText(Legend.getName()); 

if (Legend.getValue().equals("Color")){ 
      convertView.setBackgroundColor(Color.GRAY); 
      holder.value.setText("whatever you wanna show or keep it empty"); 
      //whatever you wanna do 
     } 
else{ 
holder.value.setText(Legend.getValue()); 
}