Programmatically collapse a group in ExpandableListView
When I expand a new group, can I collapse the last one expanded?
Solution 1:
Try putting this in your ExpandableListAdapter
, listView
is a reference to the ExpandableListView
itself. And lastExpandedGroupPosition
is a integer member variable defined inside your ExpandableListAdapter
.
@Override
public void onGroupExpanded(int groupPosition){
//collapse the old expanded group, if not the same
//as new group to expand
if(groupPosition != lastExpandedGroupPosition){
listView.collapseGroup(lastExpandedGroupPosition);
}
super.onGroupExpanded(groupPosition);
lastExpandedGroupPosition = groupPosition;
}
Solution 2:
Very helpful, but as Anh Tuan mentions in the comments above, I was having problems with the ExpandableListView not then scrolling back to the top of the currently selected group (it would stay at the currently scrolled position, in the middle of the group somewhere). You also need to add an onGroupClickListener() to scroll to the correct position:
@Override
public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition,
long id) {
// Implement this method to scroll to the correct position as this doesn't
// happen automatically if we override onGroupExpand() as above
parent.smoothScrollToPosition(groupPosition);
// Need default behaviour here otherwise group does not get expanded/collapsed
// on click
if (parent.isGroupExpanded(groupPosition)) {
parent.collapseGroup(groupPosition);
} else {
parent.expandGroup(groupPosition);
}
return true;
}
Solution 3:
This worked for me
expandableList.setOnGroupExpandListener(new OnGroupExpandListener() {
int previousItem = -1;
@Override
public void onGroupExpand(int groupPosition) {
if(groupPosition != previousItem )
expandableList.collapseGroup(previousItem );
previousItem = groupPosition;
}
});