Search code examples
androidandroid-studioexpandablelistviewandroid-contacts

How to collapse all the childviews above and below of a groupview in expandablelistview?


I am trying to create a contactlist app..i took an expandable listview,with a layout as a childview for each group(contact). when i click on the contact(groupView),the child will expand(layout).now when i click on another contact, i want the previous expanded groups to be collapsed..can anyone help?


Solution

  • Have the current expanded group position stored in a variable. In onGroupExpanded do the following. lastExpandedPosition contains the recently expanded child

    private int lastExpandedPosition = -1;
    private ExpandableListView lv; //your expandable listview
    ...
    
    lv.setOnGroupExpandListener(new OnGroupExpandListener() {
    
        @Override
        public void onGroupExpand(int groupPosition) {
                if (lastExpandedPosition != -1
                        && groupPosition != lastExpandedPosition) {
                    lv.collapseGroup(lastExpandedPosition);
                }
                lastExpandedPosition = groupPosition;
        }
    });