How to make RecyclerView scroll smoothly?

前端 未结 9 1482
-上瘾入骨i
-上瘾入骨i 2020-12-30 21:16

This is more like a generic question, but after lot of search and try I am not able to understand why this is so difficult to achieve. This is the closest answer I can find

9条回答
  •  猫巷女王i
    2020-12-30 22:04

    I made the scrolling smooth by overriding the calculateSpeedPerPixel(DisplayMetrics displayMetrics) method:

    public class CustomLayoutManager extends LinearLayoutManager {
    
        protected CenterLayoutManager(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 CenterSmoothScroller(recyclerView.getContext());
            smoothScroller.setTargetPosition(position);
            startSmoothScroll(smoothScroller);
        }
    
        private class CenterSmoothScroller extends LinearSmoothScroller {
    
            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 0.5f; //pass as per your requirement
            }
        }
    }
    

提交回复
热议问题