recyclerview 直接使用smoothScrollToPosition 只能让目标位置滚动到 可视的屏幕中,无法让 目标位置滚到到顶部 或者 底部
在这 我们需要创建一个类LinearLayoutManagerScrollTop来继承LinearLayoutManager重写smoothScrollToPosition 方法
同时创建一个类来继承LinearSmoothScroller重写getVerticalSnapPreference()
public class LinearLayoutManagerScrollTop extends LinearLayoutManager {
public LinearLayoutManagerScrollTop(Context context) {
super(context);
}
public LinearLayoutManagerScrollTop(Context context, int orientation, boolean reverseLayout) {
super(context, orientation, reverseLayout);
}
public LinearLayoutManagerScrollTop(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
LinearSmoothScrollerTop topScroller = new LinearSmoothScrollerTop(recyclerView.getContext());
topScroller.setTargetPosition(position);
startSmoothScroll(topScroller );
}
}
在getVerticalSnapPreference() 方法中设置 ScrollType
public class LinearSmoothScrollerTop extends LinearSmoothScroller {
private int scrollType= LinearSmoothScroller.SNAP_TO_START
public static final float DEFAULT_MILLISECONDS_PER_INCH = 25f;
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return DEFAULT_MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
}
/**
* LinearSmoothScroller.SNAP_TO_ANY 默认模式
* LinearSmoothScroller.SNAP_TO_START 顶部
* LinearSmoothScroller.SNAP_TO_END 底部
* 竖向
*/
@Override
protected int getVerticalSnapPreference() {
return scrollType;
}
/**
* LinearSmoothScroller.SNAP_TO_ANY 默认模式
* LinearSmoothScroller.SNAP_TO_START 顶部
* LinearSmoothScroller.SNAP_TO_END 底部
* 横向
*/
@Override
protected int getHorizontalSnapPreference() {
return super.getHorizontalSnapPreference();
}
}
使用
LinearLayoutManagerScrollTop manager = new LinearLayoutManagerScrollTop (this);
mRecyclerView.setLayoutManager(manager);
adapter = new ScrollTopAdapter(this);
mRecyclerView.setAdapter(adapter);
adapter.setList(list);
adapter.notifyDataSetChanged();
// 使用 smoothScrollToPosition
mRecyclerView.smoothScrollToPosition(position);