您的位置:首页 > 移动开发 > Android开发

Android ExpandableListView 长按事件 position问题

2016-12-08 19:32 357 查看
长按 ExpandableListView Item 报数组越界异常,断点 OnItemLongClickListener() 的 onItemLongClick() 方法中,发现position根据所有Group 和 已经展开的 GroupChild 数量计算,需要判断点击的是 Group 还是 GroupChild,最优解决方法: 在 OnItemLongClick()方法中判断点击类型。

bmMainListView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
@Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{

if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_GROUP)
{
long packedPosition = ((ExpandableListView) parent).getExpandableListPosition(position);

//当前Group下标
int groupPosition = ExpandableListView.getPackedPositionGroup(packedPosition);
//当前GroupChild
int childPosition = ExpandableListView.getPackedPositionChild(packedPosition);

}

/**
* 进入ExpandableListView源码,查看 PACKED_POSITION_TYPE_GROUP 类型,
/**
* The packed position represents a group.
*/
public static final int PACKED_POSITION_TYPE_GROUP = 0;

/**
* The packed position represents a child.
*/
public static final int PACKED_POSITION_TYPE_CHILD = 1;

/**
* The packed position represents a neither/null/no preference.
*/
public static final int PACKED_POSITION_TYPE_NULL = 2;
/**
* 很明显,同理判断当长按GroupChild 判断
* if (ExpandableListView.getPackedPositionType(id) == ExpandableListView.PACKED_POSITION_TYPE_CHILD)
* {
*
* }
*/
return true;
}
});


上面代码中的 packedPosition 会根据类型获得不同的值,查看源码如下

/**
* Converts a flat list position (the raw position of an item (child or group)
* in the list) to a group and/or child position (represented in a
* packed position). This is useful in situations where the caller needs to
* use the underlying {@link ListView}'s methods. Use
* {@link ExpandableListView#getPackedPositionType} ,
* {@link ExpandableListView#getPackedPositionChild},
* {@link ExpandableListView#getPackedPositionGroup} to unpack.
*
* @param flatListPosition The flat list position to be converted.
* @return The group and/or child position for the given flat list position
*         in packed position representation. #PACKED_POSITION_VALUE_NULL if
*         the position corresponds to a header or a footer item.
*/
public long getExpandableListPosition(int flatListPosition) {
if (isHeaderOrFooterPosition(flatListPosition)) {
return PACKED_POSITION_VALUE_NULL;
}

final int adjustedPosition = getFlatPositionForConnector(flatListPosition);
PositionMetadata pm = mConnector.getUnflattenedPos(adjustedPosition);
long packedPos = pm.position.getPackedPosition();
pm.recycle();
return packedPos;
}


ExpandableListView 所有坐标存在一个二维列表,packedPosition表示坐标在该列表中的位置。获取到packedPosition就可以再获取Group和GroupChild坐标了。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  android