我有一个包含2个部分的SeperatedListAdapter,每个部分包含6个项目。
代码:
listView.setAdapter(adapter);
listView.setOnItemClickListener(listViewListener);
以这种方式添加节标题和项目:
adapter = new SeparatedListAdapter(this);
adapter.addSection(entry.getKey(), new ItemAdapter(this, 0, topics.toArray(array)));
OnItemClickListener listViewListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long duration) {
Employee emp = emps.get(position - 1);
}
};
我有ArrayList:
items from section 1
Anand - 0
Sunil - 1
Suresh - 2
Dev - 3
Faran - 4
Khan - 5
items from section 2
Samba - 6
Surendra - 7
Rajesh - 9
Rakesh - 10
Satish - 11
现在在OnItemClickListener
我获得位置时,它也将节标题作为位置。
所以我做了Employee emp = emps.get(position - 1);
,但最多6项(我的arraylist 0-5)很好,但之后的位置不合适。我该如何解决这个问题?
我需要以这种方式将位置传递给我的Arrray列表
Employee emp = emps.get(position - 1);
因为我将把员工对象传递给另一个类。
也看到了这一点:
Android - SeparatedListAdapter - How to get accurate item position on onClick?
答案 0 :(得分:1)
当你在评论中评论时,你正在使用Separating Lists with Headers in Android 0.9示例。
因此adpater中有一种方法,
public Object getItem(int position) {
for(Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if(position == 0) return section;
if(position < size) return adapter.getItem(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}
返回正确的项目。
所以你只需要调用这个方法,就像{/ 1}}那样
OnItemClickListener
将以下方法添加到OnItemClickListener listViewListener = new OnItemClickListener() {
@Override
public void onItemClick(AdapterView<?> parent, View view, int position, long duration) {
Employee emp = (Employee) adapter.getItem(position); // HERE is the code to get correct item.
}
};
SeparatedListAdapter
并将其命名为
public Employee getItem(int position, ArrayList<Employee> lists) {
for(Object section : this.sections.keySet()) {
Adapter adapter = sections.get(section);
int size = adapter.getCount() + 1;
// check if position inside this section
if(position == 0) return lists.get(position);
if(position < size) return lists.get(position - 1);
// otherwise jump into next section
position -= size;
}
return null;
}