合理的展开或折叠ExapandableListView所有的组
问题:项目中需要展开折叠所有的组,用遍历所有的组可以做到,如下:
for( int i = 0, groupCount = listView.getCount(); i < groupCount; i ++ )
{
if( expanded/**/ ){ listView.collapseGroup( i ); }
else{ listView.expandGroup( i ); }
}
但是随之而来另外一个问题,当展开后,看不到点击的那个组了。我的解决思路是在展开折叠之前,先记着那个组的groupPosition,等全部展开完毕或折叠完毕后,用ExpandableListView.setSelectedGroup( groupPosition )设回到点击的那个组。
在public boolean onContextItemSelected( MenuItem item )中的MenuItem,它的方法getMenuInfo()得到的ContextMenuInfo其实是ExpandableListContextMenuInfo,用它可以得到点击的那个组的groupPosition。
代码如下:
public int getGroupPositionFromMenuInfo( ContextMenuInfo menuInfo )
{
if( menuInfo instanceof ExpandableListContextMenuInfo )
{
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo)menuInfo;
return ExpandableListView.getPackedPositionGroup( info.packedPosition );
}
return -1;
}
所有代码如下:
public int getGroupPositionFromMenuInfo( ContextMenuInfo menuInfo )
{
if( menuInfo instanceof ExpandableListContextMenuInfo )
{
ExpandableListContextMenuInfo info = (ExpandableListContextMenuInfo)menuInfo;
return ExpandableListView.getPackedPositionGroup( info.packedPosition );
}
return -1;
}
@Override public boolean onContextItemSelected( MenuItem item )
{
//...
//Think about synchronized block
int groupPosition = getGroupPositionFromMenuInfo( item.getMenuInfo() );
int groupCount = listView.getCount();
if( groupPosition < 0 || groupPosition >= groupCount ){ return true; }
for( int i = 0; i < groupCount; i ++ )
{
if( expanded/**/ ){ listView.collapseGroup( i ); }
else{ listView.expandGroup( i ); }
}
listView.setSelectedGroup( groupPosition );
//...
}
作者 NeedJava
补充:移动开发 , Android ,