ExpandableListView中item的定位问题

时间:2021-09-07 15:36:23

ExpandableListView中position一般有两个常见的参数 , 即groupPosition和childPosition . 但是当我们想要将ExpandableListView定位到某一个固定的item时 , 其提供的setSelectionFromTop(position,top)方法中的position应该是哪个参数呢 ? 其实 , groupPosition和childPosition 都不是.
我们先来了解一下ExpandableListView中position的概念 , 其有4个相关的position概念:
1.groupPosition
2.childPosition
3. Packed position:
包含了类型信息(group, child, or null for headers/footers),Group position,Child position信息的position
4.FlatListPosition
listview的原始position(包括childPosition 和 groupPosition)

转换公式:
1.FlatList position -> Packed position -> ExpandableList Group/Child positions
// a. Flat list position -> Packed position
long packedPosition = getExpandableListPosition(flatListPosition);
// b. Unpack packed position type
int positionType = getPackedPositionType(packedPosition);
//c. Unpack position values based on positionType
// 如果positionType不是空类型,就是Group,或者Child
if( positionType != PACKED_POSITION_TYPE_NULL ){
// (Child类型时也有Group信息)
groupPosition = getPackedPositionGroup(packedPosition);
// 如果是child类型,则取出childPosition
if(positionType == PACKED_POSITION_TYPE_CHILD){
childPosition = getPackedPositionChild(packedPosition);
}
}else{
Log.d(“FooLabel”, “positionType was NULL - header/footer?”);
}
2.ExpandableList Group/Child positions ->Packed position ->FlatList position
// 要从groupPosition或者childPosition转换到flatPosition就简单了
// 先由groupPosition获得packedPosition
long packedPosition = getPackedPositionForGroup(groupPosition); //获得childPosition的packedPosition则使用getPackedPositionForChild()方法
// 再由packedPosition获得flatListPosition
int flatListPosition= getFlatListPosition(packedPosition);


//从groupPos和childPos获得flatListPosition
int flatListPosition= mCardListView.getFlatListPosition(groupPos, childPos);

public int getFlatListPosition(int groupPos, int childPos) {
long packetPosition = ExpandableListView.getPackedPositionForChild(groupPos, childPos);
return mRefreshableView.getFlatListPosition(packetPosition);
}


**好了,知道了ExpandableListView的概念,我们就可以使用listview提供的setSelectionFromTop(position,top)方法了!
只要把计算出flatListPosition代入setSelectionFromTop(position,top)就可以了!**
(ps:1.top指左顶点坐标,可以通过Listview.getChildAt(index).getTop()获得
2.Listview.getChildAt(index),中index指的是屏幕可见范围内的第index项,而不是listview的第index项)