ExpandableListView.getPackedPositionGroup始终在onItemLongClick中返回0

时间:2013-07-15 16:34:09

标签: android expandablelistview

对于遇到与我同样问题的人,我会留在这里:

我尝试为OnItemLongClickListener设置ExpandableListView,并想知道点击了哪个组。根据SO上的许多问题的建议(例如this question),我使用的是ExpandableListView.getPackedPositionGroup,但它始终返回0

这是我使用的代码:

@Override
public boolean onItemLongClick(AdapterView<?> list, View view, int position, long id) {
    Log.d(D, "position: "+position);
    Log.d(D, "id: "+position);
    Log.d(D, "unpacked position: "+ExpandableListView.getPackedPositionGroup(position));

    switch(ExpandableListView.getPackedPositionType(position)) {
        case ExpandableListView.PACKED_POSITION_TYPE_CHILD:
            Log.d(D, "position type: child");
            break;

        case ExpandableListView.PACKED_POSITION_TYPE_GROUP:
            Log.d(D, "position type: group");
            break;

        case ExpandableListView.PACKED_POSITION_TYPE_NULL:
            Log.d(D, "position type: null");
            break;

        default:
            Log.wtf(D, "position type: "+ExpandableListView.getPackedPositionType(position));
    }
    return true;
}

我发现,position和id总是具有相同(正确)的值。但是,类型始终被识别为组,解压缩位置始终为0。

那么代码有什么问题?

1 个答案:

答案 0 :(得分:7)

发布代码的问题是,position不是打包位置,而是点击项目的平面位置。这意味着计算组项和可见子项。

解决方案是从平坦的位置获取打包位置,然后解压缩:

final int packedPosition = ((ExpandableListView) list).getExpandableListPosition(position);
final int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);

groupPosition现在保持所点击组的正确位置。