2013-09-23 42 views
2

在我的具體問題中,我有一個列表視圖。在此列表視圖中,我希望列表的第一行總是具有綠色的背景顏色。我做到這一點使用下面的代碼:如何在列表視圖的getview方法中引用第一個列表視圖中的可見視圖?

listView.setSelection(3); 
View element = listView.getChildAt(0); 
element.setBackgroundColor(Color.GREEN); 

的大背景下,我使用自定義適配器來填充列表視圖,爲行得到回收,綠色是在其出現新行冗餘。以下是我對getView方法的代碼:

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



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

      View first = listView.getChildAt(0); 

      if (convertView == null){ 
       convertView = inflater.inflate(R.layout.list, parent, false); 
      } 
      TextView textView = ((TextView) convertView.findViewById(R.id.textView2)); 
      textView.setText(lyrics[position]); 
      if(){ // Need to reference the first row here. 
      textView.setBackgroundColor(Color.GREEN); 
      }else { 
       textView.setBackgroundColor(Color.WHITE); 
      } 
      return convertView; 
     } 
    } 

所以在我的情況下,我需要知道在ListView第一個可見的位置,以便我可以撤消重複的背景色。有什麼辦法可以達到這個目標?只要可行,我願意改變邏輯。

+1

剛listView.getFirstVisiblePosition()? – c0ming

回答

2

ListView的觀點被回收,所以在您的適配器getView方法,你應該有 - 可能只是return convertView前:

if(position == 0) { 
    convertView.setBackgroundColor(Color.GREEN); 
} else { 
    convertView.setBackgroundColor(Color.WHITE); // or whatever color 
} 
return convertView; 

無需下面的代碼,你必須:

View element = listView.getChildAt(0); 
element.setBackgroundColor(Color.GREEN); 
+0

我正要用這段代碼回覆...... :) – Vikram

+0

它一直髮生在我身上......因爲我是一個緩慢的作家:D – gunar

+0

其實這段代碼:View element = listView.getChildAt(0); element.setBackgroundColor(Color.GREEN);是爲了着色第一個視圖,因爲它是基於時間向上滾動的。我不得不手工製作get view方法,因爲它在所有行上着色都是錯誤的。 – Skynet

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



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

     View first = listView.getChildAt(0); 

     if (convertView == null){ 
      convertView = inflater.inflate(R.layout.list, parent, false); 
     } 
     TextView textView = ((TextView) convertView.findViewById(R.id.textView2)); 
     textView.setText(lyrics[position]); 
     if(position==getFirstVisiblePosition()){ // Need to reference the first row here. 
      textView.setBackgroundColor(Color.GREEN); 
     }else { 
      textView.setBackgroundColor(Color.WHITE); 
     } 
     return convertView; 
    } 
}