以编程方式折叠ExpandableListView中的组

时间:2010-11-30 14:29:57

标签: android expandablelistview

当我展开一个新组时,我可以将最后一个组展开吗?

5 个答案:

答案 0 :(得分:121)

尝试将其放入ExpandableListAdapterlistView是对ExpandableListView本身的引用。 lastExpandedGroupPositionExpandableListAdapter中定义的整数成员变量。

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

答案 1 :(得分:20)

非常有帮助,但正如Anh Tuan在上面的评论中提到的那样,我在使用ExpandableListView时遇到问题,然后滚动回到当前所选组的顶部(它将保持在当前滚动的位置,在在某个地方的中间)。您还需要添加onGroupClickListener()以滚动到正确的位置:

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

答案 2 :(得分:17)

This为我工作

expandableList.setOnGroupExpandListener(new OnGroupExpandListener() {
    int previousItem = -1;

    @Override
    public void onGroupExpand(int groupPosition) {
        if(groupPosition != previousItem )
            expandableList.collapseGroup(previousItem );
        previousItem = groupPosition;
    }
});

答案 3 :(得分:4)

执行此操作以展开点击的群组并折叠所有其他群组

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

这对我有用。

答案 4 :(得分:2)

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