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屋!