看过网上几个长按事件的解决方案,感觉都有一些问题,所以通过查看ExpandableListView的源码,写了这篇文章,大致思路是设置长按事件监听,获取到位置后,通过ExpandableListView提供的方法计算当前点击位置的父ID和子ID,上代码
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
int groupId = -1;
int childId = -1;
long packedPosition = listView.getExpandableListPosition(position);
int itmeType = ExpandableListView.getPackedPositionType(packedPosition);
switch (itmeType) {
case 0://表示当前选中项为父条目,即Group
groupId = ExpandableListView.getPackedPositionGroup(packedPosition);
break;
case 1://表示当前选中项为子条目
groupId = ExpandableListView.getPackedPositionGroup(packedPosition);//当前子条目所在的Group
childId = ExpandableListView.getPackedPositionChild(packedPosition);//当前子条目id
break;
default:
break;
}
return false;
}
});
有一个小问题,就是长按操作后,还会出发OnChildClickListener事件,所以你要自己写变量,判断是否是长按事件