ExpandableLists in Android, I want to allow only one parent list to expand at a time

后端 未结 8 1671
难免孤独
难免孤独 2021-02-04 17:15

I want to make only one item in the parent list expand at a time, my code for the onCreate is currently the following. (It works as I want, But the method to allow only one pare

相关标签:
8条回答
  • 2021-02-04 17:56

    Easiest approach

    You can implement ExpandableListView.OnGroupExpandListener, in where you run collapseGroup() for all list groups except the one being clicked. This will do what you want.

     expandableList.setOnGroupExpandListener(new OnGroupExpandListener() {
            int previousGroup = -1;
    
            @Override
            public void onGroupExpand(int groupPosition) {
                if(groupPosition != previousGroup)
                    expandableList.collapseGroup(previousGroup);
                previousGroup = groupPosition;
            }
        });
    
    0 讨论(0)
  • 2021-02-04 17:56

    Iram Bukhari's answer is working fine. but i have did once change:

    private static int prev = -1;
    // and OnGroupExpandListener implement
    
    
     mExpandableList.setOnGroupExpandListener(new OnGroupExpandListener() {
    
                @Override
                public void onGroupExpand(int groupPosition) {
    
                    if(prev!=-1 && prev!=groupPosition )
                    {
    
                        mExpandableList.collapseGroup(prev);    
    
                    }
                    prev=groupPosition;
                }
            });
    

    I have added prev!=groupPosition as extra condition. Because if

    item 1 has clicked(opened) 
    item 1 has clicked(closed) 
    item 1 has clicked(Not opening. because prev has same position so the item is opened and collapsed immediatly ) 
    

    After Adding the condition

    item 1 has clicked(opened) 
    item 1 has clicked(closed) 
    item 1 has clicked(opened) 
    
    0 讨论(0)
提交回复
热议问题