草庐IT

android - smoothScrollToPositionFromTop() 并不总是像它应该的那样工作

coder 2023-06-07 原文

我一直在尝试让 smoothScrollToPositionFromTop() 工作,但它并不总是滚动到正确的位置。

我有一个 ListView(有 10 个项目),布局中有 10 个按钮,所以我可以滚动到列表中的每个项目。通常当我向后或向前滚动一个位置时它工作正常,但通常当我尝试向后或向前滚动超过 3 个位置时,ListView 不会完全在所选位置结束。当它失败时,它通常会关闭 0,5 到 1,5 个项目,并且滚动失败时也无法真正预测。

我还查看了 smoothScrollToPosition after notifyDataSetChanged not working in android ,但此修复对我不起作用,我不会更改任何数据。

我真的很想自动滚动到选定的列表项,但我不知道怎么做。有没有人遇到过这个问题并且知道如何解决它?

最佳答案

这是一个已知的错误。见 https://code.google.com/p/android/issues/detail?id=36062

但是,我实现了这个解决方法来处理可能发生的所有边缘情况:

首先调用smothScrollToPositionFromTop(position),然后在滚动完成后调用setSelection(position)。后一个调用通过直接跳转到所需位置来纠正不完整的滚动。这样做,用户仍然会觉得它正在被动画滚动到这个位置。

我在两个辅助方法中实现了这个解决方法:

smoothScrollToPositionFromTop()

public static void smoothScrollToPositionFromTop(final AbsListView view, final int position) {
    View child = getChildAtPosition(view, position);
    // There's no need to scroll if child is already at top or view is already scrolled to its end
    if ((child != null) && ((child.getTop() == 0) || ((child.getTop() > 0) && !view.canScrollVertically(1)))) {
        return;
    }

    view.setOnScrollListener(new AbsListView.OnScrollListener() {
        @Override
        public void onScrollStateChanged(final AbsListView view, final int scrollState) {
            if (scrollState == SCROLL_STATE_IDLE) {
                view.setOnScrollListener(null);

                // Fix for scrolling bug
                new Handler().post(new Runnable() {
                    @Override
                    public void run() {
                        view.setSelection(position);
                    }
                });
            }
        }

        @Override
        public void onScroll(final AbsListView view, final int firstVisibleItem, final int visibleItemCount,
                                 final int totalItemCount) { }
    });

    // Perform scrolling to position
    new Handler().post(new Runnable() {
        @Override
        public void run() {
            view.smoothScrollToPositionFromTop(position, 0);
        }
    });
}

getChildAtPosition()

public static View getChildAtPosition(final AdapterView view, final int position) {
    final int index = position - view.getFirstVisiblePosition();
    if ((index >= 0) && (index < view.getChildCount())) {
        return view.getChildAt(index);
    } else {
        return null;
    }
}

关于android - smoothScrollToPositionFromTop() 并不总是像它应该的那样工作,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14479078/

有关android - smoothScrollToPositionFromTop() 并不总是像它应该的那样工作的更多相关文章

随机推荐