到达底部后自动滚动到回收站视图顶部的最佳方法是什么?

What is the best way to automatically scroll to the top of a recycler view after hitting the bottom?

我正在创建一个显示卡片回收视图的 android 应用程序。我已经实现了一个自动滚动功能作为我的线性布局管理器的一部分,它将平滑滚动到 recyclerview 中的最后一个元素。

我希望列表在检测到最后一个元素可见后快速返回到 recyclerview 的顶部。

这是我的自定义布局管理器的代码。

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);
    }
}

您可能需要附加一个 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) 来检查您是否点击了最后一项,然后滚动回到顶部。