How can i control the scrolling speed of recyclerView.smoothScrollToPosition(position)

前端 未结 5 618
感情败类
感情败类 2020-11-28 23:18

I have a recycler view... and i want a smooth scrolldown and then scrollup to it programatically to show the complete content in it to user .... And i m able to do this by<

5条回答
  •  盖世英雄少女心
    2020-11-28 23:43

    Just to improve on the answer a little:

    public class SpeedyLinearLayoutManager extends LinearLayoutManager {
    
        private static final float MILLISECONDS_PER_INCH = 5f; //default is 25f (bigger = slower)
    
        public SpeedyLinearLayoutManager(Context context) {
            super(context);
        }
    
        public SpeedyLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
            super(context, orientation, reverseLayout);
        }
    
        public SpeedyLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
            super(context, attrs, defStyleAttr, defStyleRes);
        }
    
        @Override
        public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
    
            final LinearSmoothScroller linearSmoothScroller = new LinearSmoothScroller(recyclerView.getContext()) {
    
                @Override
                public PointF computeScrollVectorForPosition(int targetPosition) {
                    return super.computeScrollVectorForPosition(targetPosition);
                }
    
                @Override
                protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
                    return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
                }
            };
    
            linearSmoothScroller.setTargetPosition(position);
            startSmoothScroll(linearSmoothScroller);
        }
    }
    

    And then set SpeedyLayoutManager to your RecyclerView:

    recyclerView.setLayoutManager(new SpeedyLinearLayoutManager(context, SpeedyLinearLayoutManager.VERTICAL, false);
    

提交回复
热议问题