在Android中迭代ListView项

poc*_*coa 6 iteration android listview listviewitem

我想将项目列表迭代到ListView中.由于getChildCount()函数的奇怪行为(仅返回可见项目计数),下面的代码不足以将所有项目迭代到列表中.

for (int i = 0; i < list.getChildCount(); i++) {
   item = (View)list.getChildAt(i);
   product = (Product)item.getTag();
   // make some visual changes if product.id == someProductId
}
Run Code Online (Sandbox Code Playgroud)

我的屏幕显示7个结果,当列表中有超过7个项目时,无法访问第8个项目.只有可见项目..

我应该使用ListIterator吗?

谢谢.

kco*_*ock 1

您需要自定义列表适配器的getView()方法,并将检查放入其中以检查当前项目的 id 是否匹配:

Product product = items.get(position);
if(product.id == someProductId) {
    //make visual changes
} else {
    //reset visual changes to default to account for recycled views
}
Run Code Online (Sandbox Code Playgroud)

由于通常只有可见项目仅在特定时间存在,因此只要需要查看更多项目,就会调用 getView。它们是在那时创建的,通常从列表中现在不可见的项目中回收视图(因此,如果条件不匹配,您要重置更改)。