RecyclerView 横向滑动,选中Item默认滚动到屏幕中间

tech2025-09-10  31

1、创建类

public class CenterLayoutManager extends LinearLayoutManager { public CenterLayoutManager(Context context) { super(context); } public CenterLayoutManager(Context context, int orientation, boolean reverseLayout) { super(context, orientation, reverseLayout); } public CenterLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) { super(context, attrs, defStyleAttr, defStyleRes); } @Override public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) { RecyclerView.SmoothScroller smoothScroller = new CenterSmoothScroller(recyclerView.getContext()); smoothScroller.setTargetPosition(position); startSmoothScroll(smoothScroller); } private static class CenterSmoothScroller extends LinearSmoothScroller { public CenterSmoothScroller(Context context) { super(context); } @Override public int calculateDtToFit(int viewStart, int viewEnd, int boxStart, int boxEnd, int snapPreference) { return (boxStart + (boxEnd - boxStart) / 2) - (viewStart + (viewEnd - viewStart) / 2); } @Override protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) { return 100f / displayMetrics.densityDpi; } } }

 

2、设置

CenterLayoutManager layoutManager=new CenterLayoutManager(context, LinearLayoutManager.HORIZONTAL, false); recyclerView.setLayoutManager(layoutManager);

item点击时调用

layoutManager.smoothScrollToPosition(recyclerView, new RecyclerView.State(), position);
最新回复(0)