ExpandableListView.getPackedPositionGroup always returns 0 in onItemLongClick
Asked Answered
V

2

1

For those encountering the same problem as me I'll leave this here:

I was trying to set up a OnItemLongClickListener for an ExpandableListView and wanted to know which group was clicked. Following the advice of many questions here on SO (for example this question) I was using ExpandableListView.getPackedPositionGroup, however it always returned 0.

Here's the code I used:

@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;
}

What I found is that position and id always had the same (correct) value. However, the type was always recognised as group and the unpacked position was always 0.

So what is wrong with that code?

Vesuvianite answered 15/7, 2013 at 16:34 Comment(0)
V
7

The problem with the posted code is, that position isn't a packed position but the flat position of the clicked item. That means that group items as well as visible child items are counted.

The solution is to get the packed position from the flat one and than unpack that:

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

groupPosition now holds the correct position of the clicked group.

Vesuvianite answered 15/7, 2013 at 16:34 Comment(0)
C
0

Use :

int groupPosition = ExpandableListView.getPackedPositionGroup(id);

Instead of

int groupPosition = ExpandableListView.getPackedPositionGroup(position);

Actually the 4th item in the longClickListener function is the packed Position only. Android studio when generating, names it as id

public boolean onItemLongClick
(AdapterView<?> list, View view, int position, long id -> this is packedPosition)
Clinkerbuilt answered 7/12, 2021 at 6:49 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.