是否有 ListView 的 smoothScrollToPositionFromTop() 的替代品?对于 RecyclerView?我正在尝试将 ListView 代码迁移到 RecyclerView,但我在任何地方都看不到它的 RecyclerView 版本。
有一种方法叫做 RecyclerView.smoothScrollToPosition() ,但是你不能定义相对于屏幕顶部元素的偏移量(我需要列表滚动到一个位置,并且总是在该位置是列表中的第一个可见子元素时停止)。
最佳答案
要始终将目标位置平滑滚动到顶部,您可以使用像这样的自定义 LinearLayoutManager:
public class CustomLinearLayoutManager extends LinearLayoutManager {
private Context context;
public CustomLinearLayoutManager(Context context) {
super(context);
this.context = context;
}
public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
this.context = context;
}
public CustomLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
this.context = context;
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
LinearSmoothScroller smoothScroller = new LinearSmoothScroller(context) {
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return CustomLinearLayoutManager.this.computeScrollVectorForPosition(targetPosition);
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_START;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
}
关于android - RecyclerView smoothScroolToPositionFromTop(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410884/