在 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/31235183/