在RecyclerView上,我可以通过以下方法突然滚动到所选项目的顶部:
((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(position, 0);
但是,这会突然将项目移到最高位置。我想移动到一个项目的顶部平滑的。
我也试过:
recyclerView.smoothScrollToPosition(position);
但是,它不能很好地工作,因为它没有将项目移动到选定的位置到顶部。它只是滚动列表,直到位置上的项目可见为止。
发布于 2017-04-19 20:52:01
RecyclerView
设计为可扩展,因此不需要仅仅为了执行滚动就将LayoutManager
(作为droidev suggested)子类化。
相反,只需创建一个带有首选项SNAP_TO_START
的SNAP_TO_START
RecyclerView.SmoothScroller smoothScroller = new LinearSmoothScroller(context) {
@Override protected int getVerticalSnapPreference() {
return LinearSmoothScroller.SNAP_TO_START;
}
};
现在,将要滚动到的位置设置为:
smoothScroller.setTargetPosition(position);
并将该SmoothScroller传递给LayoutManager:
layoutManager.startSmoothScroll(smoothScroller);
发布于 2015-09-28 08:53:50
为此,您必须创建一个自定义LayoutManager
public class LinearLayoutManagerWithSmoothScroller extends LinearLayoutManager {
public LinearLayoutManagerWithSmoothScroller(Context context) {
super(context, VERTICAL, false);
}
public LinearLayoutManagerWithSmoothScroller(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) {
RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext());
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
private class TopSnappedSmoothScroller extends LinearSmoothScroller {
public TopSnappedSmoothScroller(Context context) {
super(context);
}
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return LinearLayoutManagerWithSmoothScroller.this
.computeScrollVectorForPosition(targetPosition);
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_START;
}
}
}
将其用于您的RecyclerView并调用smoothScrollToPosition。
例子:
recyclerView.setLayoutManager(new LinearLayoutManagerWithSmoothScroller(context));
recyclerView.smoothScrollToPosition(position);
这将滚动到指定位置的RecyclerView项的顶部。
希望这能有所帮助。
发布于 2018-12-31 11:23:40
这是我在Kotlin中编写的一个扩展函数,用于RecyclerView
(基于@Paul答案):
fun RecyclerView.smoothSnapToPosition(position: Int, snapMode: Int = LinearSmoothScroller.SNAP_TO_START) {
val smoothScroller = object : LinearSmoothScroller(this.context) {
override fun getVerticalSnapPreference(): Int = snapMode
override fun getHorizontalSnapPreference(): Int = snapMode
}
smoothScroller.targetPosition = position
layoutManager?.startSmoothScroll(smoothScroller)
}
像这样使用它:
myRecyclerView.smoothSnapToPosition(itemPosition)
https://stackoverflow.com/questions/31235183
复制相似问题