ExpandableListview - 当单击另一个项目时,如何关闭先前打开的项目?

时间:2017-03-16 09:26:35

标签: android expandablelistview

如果在expandablelistview上点击了其他项目,如何关闭之前打开的项目?

我参考本教程http://www.androidhive.info/2013/07/android-expandable-list-view-tutorial/ 但是当我点击新项目时,prevoius项目将不会关闭。

3 个答案:

答案 0 :(得分:6)

因此,您一次只需要一个(或零)扩展组。对?当您展开另一个组时,以下代码将关闭先前展开的组。试试吧。

你去吧

final int[] prevExpandPosition = {-1};
    expandableListView.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
        @Override
        public void onGroupExpand(int groupPosition) {
            if (prevExpandPosition[0] >= 0 && prevExpandPosition[0] != groupPosition) {
                expandableListView.collapseGroup(prevExpandPosition[0]);
            }
            prevExpandPosition[0] = groupPosition;
        }
    });

答案 1 :(得分:2)

您可以实施ExpandableListView.OnGroupClickListener,您需要为所有列表组调用collapseGroup(),但点击的列表组除外:

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

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

答案 2 :(得分:1)

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

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