2011-08-09 33 views
0

我將簡單的數據添加到列表視圖(名稱和時間),我希望能夠爲每個表格行在白色和灰色背景之間切換。我目前在xml文件中設置背景顏色。如何在Listviews之間交替顏色?

我使用從http://saigeethamn.blogspot.com/2010/04/custom-listview-android-developer.html

感謝

編輯代碼 我的代碼看起來像這樣

//R.layout.custom_list_view is just a list view with grey background 
    //(I want it white for every other one) 
    //On Create section 
    setContentView(R.layout.custom_list_view); 

    SimpleAdapter adapter = new SimpleAdapter(
      this, 
      list, 
      R.layout.custom_row_view, 
      new String[] {"pen","price"}, 
      new int[] {R.id.text1,R.id.text2} 
      ); 
    //see function below 
    populateList(); 
    setListAdapter(adapter); 
} 

static final ArrayList<HashMap<String,String>> list = 
    new ArrayList<HashMap<String,String>>(); 

private void populateList() { 
    //for loop would go here 
    HashMap<String,String> temp = new HashMap<String,String>(); 
    temp.put("pen","MONT Blanc"); 
    temp.put("price", "200.00$"); 
    list.add(temp); 

    HashMap<String,String> temp2 = new HashMap<String,String>(); 
    temp2.put("pen","Parker"); 
    temp2.put("price", "400.00$"); 
    list.add(temp2); 
    //theres no place to change the background of my listview 

最後的編輯。這是一個簡單的解決方案http://ykyuen.wordpress.com/2010/03/15/android-%E2%80%93-applying-alternate-row-color-in-listview-with-simpleadapter/ 將SimpleAdapter適配器更改爲在網站中找到的自定義SpecialAdapter。謝謝大家的幫助

回答

2

你應該做的實現自定義的適配器和設置背景顏色有:

public View getView(int position, View convertView, ViewGroup parent) { 
     ViewHolder holder; 
     View convertViews; 
     if (convertView == null) { 
      convertViews = mInflater.inflate(R.layout.startingsquadlistview, null); 
      holder = new ViewHolder(); 
      holder.text = (TextView) convertView.findViewById(R.id.textview); 
      convertViews.setTag(holder); 
     } else { 
      convertViews = convertView; 
      holder = (ViewHolder) convertViews.getTag(); 
     } 

     if(position % 0) { 
      convertView.setBackground(context.getResources().getColor(R.color.col1); 
     else 
      convertView.setBackground(context.getResources().getColor(R.color.col2); 

     return convertViews; 
    } 
+0

感謝您的提示,但我不太明白你在答案中寫的是什麼。你能幫我調整一下listview嗎?對不起,我只是困惑 – Sean

+0

@肖恩你必須爲它實現自定義適配器。在你的情況下ArrayAdapter是你需要的。 ArrayAdapter的主要方法是getView()。這是我的答案中的例子。在它中你還應該手動設置所有文本的文本或者調用super.getView(position,convertView,parent)。在這種情況下,它將返回您可以使用的視圖,而不是內容視圖。你可以設置背景 – Maxim

0

您可以創建一個自定義列表適配器,並在那裏創建一個名爲'alternateColor'的全局布爾變量。然後在你的getView()函數把這個(在這種情況下,「電視」是你的TextView):

if (alternateColor) 
{ 
    tv.setBackgroundColor(Color.GRAY); 
    alternateColor = false; 
} 
else if (!alternateColor) 
{ 
    tv.setBackgroundColor(Color.WHITE); 
    alternateColor = true; 
} 

點擊here有關如何使自定義列表適配器的教程。

+1

你應該做的唯一的事情就是讓顏色資源throught資源引用。直接引用在這種情況下無法正常工作 – Maxim

+0

@Maxim我現在正在查看類似的問題。你會推薦哪兩個答案是更好的選擇? – jamesc

+0

@jamesw其實這個想法是一樣的。在一種情況下,您設置了項目的背景。在textview的另一個背景。這取決於你的需求。但請記住關於通過資源不足來着色的問題 – Maxim