RecyclerView - 如何平滑滚动到某个位置的项目顶部? [英] RecyclerView - How to smooth scroll to top of item on a certain position?
问题描述
在 RecyclerView 上,我可以使用以下方法突然滚动到所选项目的顶部:
On a RecyclerView, I am able to suddenly scroll to the top of a selected item by using:
((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, 0);
然而,这突然将项目移动到顶部位置.我想平滑地移动到项目的顶部.
However, this abruptly moves the item to the top position. I want to move to the top of an item smoothly.
我也试过:
recyclerView.smoothScrollToPosition(position);
但它不能很好地工作,因为它不会将项目移动到选择到顶部的位置.它只是滚动列表,直到位置上的项目可见.
but it does not work well as it does not move the item to the position selected to the top. It merely scrolls the list until the item on the position is visible.
推荐答案
RecyclerView
被设计为可扩展的,因此不需要将 LayoutManager
子类化(如 droidev 建议) 只是为了执行滚动.
RecyclerView
is designed to be extensible, so there is no need to subclass the LayoutManager
(as droidev suggested) just to perform the scrolling.
相反,只需创建一个带有首选项 SNAP_TO_START
的 SmoothScroller
:
Instead, just create a SmoothScroller
with the preference SNAP_TO_START
:
RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
现在您设置要滚动到的位置:
Now you set the position where you want to scroll to:
smoothScroller.setTargetPosition(position);
并将该 SmoothScroller 传递给 LayoutManager:
and pass that SmoothScroller to the LayoutManager:
layoutManager.startSmoothScroll(smoothScroller);
这篇关于RecyclerView - 如何平滑滚动到某个位置的项目顶部?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!