ExpandableListview OnGroupClickListener未触发

时间:2013-08-17 17:40:53

标签: android expandablelistview onclicklistener expandablelistadapter

我正在关注此事:Programmatically collapse a group in ExpandableListView。我希望用户能够一次只扩展一个组并平滑地滚动到正确的位置。我编写了一个实现OnGroupClickListener的自定义适配器:

public class CategoriesListAdapter extends BaseExpandableListAdapter implements OnGroupClickListener {

    private ExpandableListView expListView;
    private int lastExpandedGroupPosition = -1;

    // I get the expListView in the constructor...

    @Override
    public boolean onGroupClick(ExpandableListView parent, View view, int groupPosition, long id) {

        parent.smoothScrollToPosition(groupPosition);

        if (parent.isGroupExpanded(groupPosition)) {
            parent.collapseGroup(groupPosition);
        } else {
            parent.expandGroup(groupPosition);
        }

        return true;
    }

    @Override
    public void onGroupExpanded(int groupPosition) {

        if (groupPosition != lastExpandedGroupPosition) {
            expListView.collapseGroup(lastExpandedGroupPosition);
        }

        super.onGroupExpanded(groupPosition);
        lastExpandedGroupPosition = groupPosition;
    }
}

不幸的是onGroupClick事件永远不会被触发...(我在方法中放了一些日志)。我也试过了:

expListView.setOnGroupClickListener(new OnGroupClickListener() {
    @Override
    public boolean onGroupClick(ExpandableListView parent, View view, int groupPosition, long id) {
        // Same as above...
    });
}

这个替代方案的结果相同......任何想法?

1 个答案:

答案 0 :(得分:4)

我建议您先检查导入(未在问题中显示),并确保已导入android.widget.ExpandableListView.OnGroupClickListener

或替换:new OnGroupClickListener() {

new android.widget.ExpandableListView.OnGroupClickListener {

编辑:

我还注意到你在boolean onGroupClick(...)的正文中返回“true”,表示“处理了点击”,并且群组永远不会折叠,展开。

如果你想扩展,你应该返回false。所以我建议你这样做:

expListView.setOnGroupClickListener(new OnGroupClickListener() {
            @Override
            public boolean onGroupClick(ExpandableListView parent, View v, int groupPosition, long id) {
                Log.d("onGroupClick:", "worked");

                parent.smoothScrollToPosition(groupPosition);

                if (parent.isGroupExpanded(groupPosition)) {
                    parent.collapseGroup(groupPosition);
                } else {
                   parent.expandGroup(groupPosition);
                }

                return false;
            }
        });