Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Programmatically collapse a group in ExpandableListView

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

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

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

Do this to expand the clicked group and collapse all others

public void onGroupExpand(int groupPosition)
{
    for (int i = 0; i < len; i++)
    {
        if (i != groupPosition)
        {
            expandableListDetailsLevel.collapseGroup(i);
        }
    }
}

It's working for me.


    @Override
    public void onGroupExpanded(int groupPosition) {
        for(int i=0;i<mGroupCollection.size();i++){
            if(i==groupPosition){
                System.out.println("Nothing");
                         }
            else{
                   mExpandableListView.collapseGroup(i);
            }

        }
        super.onGroupExpanded(groupPosition);
    }