2011-11-18 60 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(); 
    } 

在上述情况下,我已经从列表视图中提取复选框视图。