gpt4 book ai didi

android - RecyclerView - 如何平滑滚动到某个位置的项目顶部?

转载 作者:行者123 更新时间:2023-12-01 16:21:54 26 4
gpt4 key购买 nike

在 RecyclerView 上,我可以使用以下方法突然滚动到所选项目的顶部:

((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, 0);

但是,这突然将项目移动到顶部位置。我想平滑地移动到某个项目的顶部。

我也尝试过:

recyclerView.smoothScrollToPosition(position);

但它不能很好地工作,因为它不会将项目移动到顶部选定的位置。它只是滚动列表,直到该位置上的项目可见。

最佳答案

RecyclerView 被设计为可扩展的,因此无需子类化 LayoutManager (如 droidev suggested )即可执行滚动。

相反,只需使用首选项 SNAP_TO_START 创建一个 SmoothScroller:

RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};

现在您设置要滚动到的位置:

smoothScroller.setTargetPosition(position);

并将 SmoothScroller 传递给 LayoutManager:

layoutManager.startSmoothScroll(smoothScroller);

关于android - RecyclerView - 如何平滑滚动到某个位置的项目顶部?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62249096/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com