Programmatically collapse a group in ExpandableListView

user2443607 picture user2443607 · Nov 30, 2010 · Viewed 42.8k times · Source

When I expand a new group, can I collapse the last one expanded?

Answer

danh32 picture danh32 · Nov 30, 2010

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