2017-02-16 42 views
0

我有一個適配器從檢索的json填充我的Listview。 我想改變某些細胞的顏色,這取決於位置,即位置1的藍色位置2紅色等等。但是使用當前代碼我可以得到所需的效果,但是當我向下滾動列表時它會重複。我知道這是因爲該視圖令人耳目一新,但不知道如何解決它。Android列表視圖改變certian位置的顏色

public class ListAdapter extends BaseAdapter { 

MainActivity main; 

ListAdapter(MainActivity main) { 
this.main = main; 
} 

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

@Override 
public Object getItem(int position) { 
return null; 
} 

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

static class ViewHolderItem { 
TextView name; 
TextView code; 
TextView pts; 

} 

@Override 
public View getView(int position, View convertView, ViewGroup parent){ 
ViewHolderItem holder = new ViewHolderItem(); 
if (convertView == null) { 
LayoutInflater inflater = (LayoutInflater) main.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     convertView = inflater.inflate(R.layout.cell, null); 

     holder.name = (TextView) convertView.findViewById(R.id.name); 
     holder.code = (TextView) convertView.findViewById(R.id.code); 
     holder.pts = (TextView) convertView.findViewById(R.id.pts); 

     convertView.setTag(holder); 
} 
else { 
      holder = (ViewHolderItem) convertView.getTag(); 
} 

holder.name.setText(this.main.countries.get(position).name); 
holder.code.setText(this.main.countries.get(position).code); 
holder.pts.setText(this.main.countries.get(position).pts); 

if (position == 1) { 
holder.name.setBackgroundColor(Color.parseColor("#FFFFFF")); 

} 

return convertView; 

} 

} 
+0

提供其他條件與您想要的顏色textview背景 – pkgrover

+0

謝謝,我嘗試過,但它仍然在整個列表中重複。 –

+1

您可以創建列表大小的顏色列表,並根據位置從colorList中獲取所需的顏色 – Roish

回答

0

列表中的視圖將被回收,這是滾動到外部的項目視圖砂漿是滾動到屏幕中的條目重用使用這樣的代碼

if (position == 1) { 
    holder.name.setBackgroundColor(Color.parseColor("#FFFFFF")); 
} else { 
    holder.name.setBackgroundColor(...) 
} 

或者,如果你想只有兩個項目的顏色來劃分列表:。

if(position % 2 == 0) view.setBackgroundColor(Color.rgb(224, 224, 235)); 
if(position % 2 == 1) view.setBackgroundColor(The normal color you should set); 
0

如果我理解正確的 - 你只在位置1 可能發生,因爲你重新使用在getView給出convertView反覆,而不是看這個顏色,這意味着你已經創建並已經使用了View,它具有背景色並具有較老的屬性,並且爲它提供了新的屬性和數據。 因此,在這種情況下 - 它可能具有舊顏色,並且因爲您不會爲每個位置提供顏色,該顏色會與它保持一致。

我認爲在這種情況下 -

switch(position){ 
    case 1: 
      holder.name.setBackgroundColor(Color.parseColor("#FFFFFF")); 
      break; 
    case 2: 
      holder.name.setBackgroundColor(Color.parseColor("#EEEEEE")); 
      break; 
    case 3: 
      holder.name.setBackgroundColor(Color.parseColor("#000000")); 
      break; 
    case 4: 
      holder.name.setBackgroundColor(Color.parseColor("#DDDDDD")); 
      break; 
    case default: 
      holder.name.setBackgroundColor(Color.parseColor("#ABCDEF")); 
      break; 
} 

將解決回收色差問題。 (在開關選擇範圍內添加儘可能多的顏色,或者按照上面提到的方法創建顏色陣列並根據位置進行更改)

相關問題