Android Expandable ListView - 如何平滑滚动到组内的子位置?

时间:2014-08-24 07:01:54

标签: android expandablelistview

我有一个可扩展的列表视图。我的一个团体Group1有15个孩子。如何在点击并展开Group1时平滑滚动到第10个孩子?

感谢。

1 个答案:

答案 0 :(得分:3)

覆盖适配器的onGroupExpanded方法,并使用smoothScrollToPosition ExpandableListView方法调用一种方法。类似的东西:

@Override
public void onGroupExpanded(int groupPosition) {
    super.onGroupExpanded(groupPosition);
    // If it's the first group
    if (groupPosition == 0) {
        int scrollTo = groupPosition + 15;
        mExpList.smoothScrollToPositionFromTop(scrollTo, 0);
    }
}

现在请记住,如果在groupPosition之前扩展了其他群组,则scrollTo必须考虑到这一点。因此,您可能希望将所有扩展组位置(及其子项计数)保存到数组中,并在每次调用onGroupExpandedonGroupCollapsed时循环它们。

可能看起来像这样:

@Override
public void onGroupExpanded(int groupPosition) {
    super.onGroupExpanded(groupPosition);
    groupStates.put(groupPosition, 1);
    childrenCount.put(groupPosition, getChildrenCount(groupPosition));
    // Loop the group states
    int scrollTo = 0;
    for (int i=0; i<groupStates.size(); i++) {
        int position = groupStates.keyAt(i);
        // Cancel the loop if reached a further expanded group
        if (position > groupPosition) break;

        // 1 is the group to be skipped + its children count
        scrollTo += 1 + childrenCount.get(position);
    }
    // You can select specific child of the recently expanded group, to scroll to
    int childToScrollTo = 15; // make sure is an existing child
    // -1 because positions begin at index 1
    scrollTo = scrollTo - 1 + childToScrollTo;
    mExpList.smoothScrollToPositionFromTop(scrollTo, 0);
}

@Override
public void onGroupCollapsed(int groupPosition) {
    super.onGroupCollapsed(groupPosition);
    groupStates.remove(groupPosition);
    childrenCount.remove(groupPosition);
}

然而,这是未经测试的,所以请确保您正确测试。