0

I'm creating an android app that displays a recyclerview of cards. I have implemented an auto-scroll feature as part of my linear layout manager that will smoothscroll to the last element in the recyclerview.

I would like the list to snap back to the top of the recyclerview once it has detected that the last element is visible.

Here is the code for my custom layout manager.

public class ScrollLayoutManager extends LinearLayoutManager {

    private static final float MILLISECONDS_PER_INCH = 10000f; //default is 25f (bigger = slower)

    public ScrollLayoutManager(Context context) {
        super(context);
    }

    public ScrollLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
    }

    public ScrollLayoutManager(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);
    }
}
Sam
  • 348
  • 1
  • 10
  • check this thread https://stackoverflow.com/questions/40726438/android-detect-when-the-last-item-in-a-recyclerview-is-visible – Khojiakbar Jul 04 '19 at 14:45

1 Answers1

0

You might want attach a RecyclerView.OnScrollListener (docs) to your RecyclerView and override onScrolled() and use either findLastCompletelyVisibleItemPosition() (docs) or findLastVisibleItemPosition() (docs), depending on your needs, in combination with getItemCount() (docs) to check if you hit the last item and then scroll back to the top.

Raimo
  • 1,494
  • 1
  • 10
  • 19