我有CustomAdapter,我用它来填充ListView和一些数据。
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();
}
}
}
});
但是我的所有listview元素都具有这两个变量中第一个元素的值。
那么我如何才能像item.next();
那样验证listview中的所有项目?
抱歉,在检查listview项目的变量以了解我的问题后,我将提供有关我正在做的事情的更多信息。
我还有一个适配器:
SomeAnotherAdapter adapterPr = new SomeAnotherAdapter(this, R.layout.list_tem_another, itemsAnother);
还有一个列表视图:
listViewAnother.setAdapter(adapterPr);
首先我理解,第一个变量应该来自第一个listview而第二个变量来自另一个listview。
在这个listViewAnother我有很多项目,其中有一些“id”。例如,1st,5th和20th元素的id为90,其他元素的id为100.我们可以说,第一个listview中的项目也有“id”。
因此,我必须检查if(first variable = second variable)
,然后在listViewAnother中仅显示id等于listView中单击项的ID的项。
我试过:adapterPr.remove(item2);
然后我理解,我需要所有的项目,因为我可以回到listView并按下另一个需要删除元素的项目。
现在,希望我提供了完整的信息,您将能够帮助我改进我的代码。
当您单击适配器的一个元素时,是否需要对适配器的每个元素执行检查?如果没有,您不需要循环。如果这样做,你的循环应该迭代原始列表,并且根本不需要适配器位置。
通常,在使用适配器和列表时,应使用适配器的位置和适配器的数据集来执行任何任务。使用适配器位置从原始列表中获取项目不是一个好习惯。
只需设置一个onItemClickListener
,从适配器获取相应的item
,并从那里做你需要的:
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) {
SomeItem item = adapter.getItem(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();
}
}
});