【发布时间】:2019-04-10 22:38:28
【问题描述】:
我有 CustomAdapter,我用它来用一些数据填充 ListView。
ListView 中的每个元素都有两个变量。对于每个列表视图(在 onItemClick 方法中),我必须检查这些变量,如果它们相同 - 执行一些代码,如果它们不同 - 执行另一个代码,例如 Toast.makeText(EPG.this, "Variables are different", Toast.LENGTH_SHORT).show();
所以我试过这个:
private List<SomeItem> items = new ArrayList();
//items were created
SomeAdapter adapter = new SomeAdapter(this, R.layout.list_item, items);
listView.setAdapter(adapter);
listView.setOnItemClickListener(new android.widget.AdapterView.OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
for(int i=0; i<=items.size(); i++) {
SomeItem item = items.get(position);
String tmpCI = item.getFirstVariable();
String tmpPCI = item.getecondVariable();
if (!tmpCI.equals(tmpPCI)) {
//some code
} else {
Toast.makeText(EPG.this, "Variables are different", Toast.LENGTH_SHORT).show();
}
}
}
});
但是我所有的列表视图元素都有这两个变量中第一个元素的值。
那么我该如何做类似item.next(); 的操作来验证列表视图中的所有项目?
统一更新:
抱歉,在检查列表视图项的变量以了解我的问题后,我将提供有关我在做什么的更多信息。
我还有一个适配器:
SomeAnotherAdapter adapterPr = new SomeAnotherAdapter(this, R.layout.list_tem_another, itemsAnother);
还有一个列表视图:
listViewAnother.setAdapter(adapterPr);
首先我明白,第一个变量应该来自第一个列表视图,第二个变量应该来自另一个列表视图。
在这个 listViewAnother 我有很多项目,其中有一些“id”。例如,第 1、第 5 和第 20 个元素的 id 为 90,其他元素的 id 为 100。 我们可以说,第一个列表视图中的项目也有“id”。
所以我必须检查if(first variable = second variable),然后在listViewAnother 中只显示id 等于listView 中单击项目的ID 的项目。
我试过:adapterPr.remove(item2);,但后来我明白了,我需要所有项目,因为我可以返回 listView 并按另一个需要那些已删除元素的项目。
现在,希望我提供了完整的信息,您将能够帮助我改进我的代码。
【问题讨论】:
-
如果要比较相同(点击)项的变量值,则无需循环。
-
提供了有关我的问题的更多信息
-
如果您想迭代整个 ArrayList,请尝试将:
SomeItem item = items.get(position);替换为SomeItem item = items.get(i);。 items.get(position) 在 for 循环中只是重复获取相同的数据。希望有帮助!