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

最佳答案

重写适配器的onGroupExpanded方法并调用其中一个smoothScrollToPosition方法。类似于:

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

现在请记住,如果在ExpandableListView之前有其他组扩展,groupPosition将必须考虑到这一点。因此,您可能希望将所有展开的组位置(及其子级计数)保存到一个数组中,并在每次调用scrollToonGroupExpanded时循环它们。
可能是这样的:
@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);
}

但这是未经测试,所以请确保您测试它正确。

09-10 14:28