2011-11-18 59 views
1

我有一個ListView已經由包含使用適配器的數據的行填充。 行佈局是「RelativeLayout」類型,包含各種視圖對象,其中一個是「@ + id/bar_fill」。如何獲取複雜ListView行視圖中的視圖?

我有一個循環遍歷ListView的所有孩子,我想「獲得」我上面提到的視圖項目。

我正在使用的代碼是:

ListView list = getListView(); 
int count = list.getCount(); 
for (int i = 0; i < count; i++) 
{ 
    RelativeLayout row = (RelativeLayout) list.getChildAt(i); 
    View bar = row.findViewById(R.id.bar_fill);   
} 

然而,當它到達崩潰的最後一行。當我評論它並做了

System.out.println(findViewById(R.id.bar_fill)); 

它返回空值。

我在做什麼錯?

回答

3

覆蓋自定義適配器中的此功能。

public View getView(int position, View convertView, ViewGroup parent); 
View v = convertView; 
    if (v == null) { 
     LayoutInflater vi = (LayoutInflater) c 
       .getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
     v = vi.inflate(id, null); 
    } 

現在一樣,如果你想從列表視圖行項目一定的TextView然後像這樣做:

TextView t1 = (TextView) v.findViewById(com.pis.prototype.R.id.TextView01); 

T1是你需要的視圖現在...:P

+2

這是正確的想法,但您應該使用ViewHolder,如圖所示,以避免convertView!= null時額外調用findViewById。在許多設備上,它可以在性能上產生顯着的差異:http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/List14.html – adamp

+0

不錯的adamp。非常感謝。 –

0

如果你想要在列表視圖中獲取已更新/創建的項目,並希望從某一行獲取某些視圖。然後這樣做..:

for (int i = 0; i < yourCustomAdapter.size(); i++) { 

     View viewRow = listViewParts.getChildAt(i); 

     CheckBox chkBox = (CheckBox) viewRow 
       .findViewById(R.id.checkBox); 
     yourCustomAdapter.get(i).attachmentCheck = chkBox 
       .isChecked(); 
    } 

在上述情況下,我已經從列表視圖中提取複選框視圖。