【问题标题】:What is the best way to automatically scroll to the top of a recycler view after hitting the bottom?到达底部后自动滚动到回收站视图顶部的最佳方法是什么?
【发布时间】:2019-07-04 22:46:39
【问题描述】:

我正在创建一个显示卡片回收视图的 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);
    }
}

【问题讨论】:

标签: java android android-adapter android-recyclerview


【解决方案1】:

您可能希望将RecyclerView.OnScrollListener (docs) 附加到您的RecyclerView 并覆盖onScrolled() 并使用findLastCompletelyVisibleItemPosition() (docs) 或findLastVisibleItemPosition() (docs),具体取决于您的需要结合getItemCount() (docs) 来检查是否点击了最后一项,然后再滚动回顶部。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-01-26
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多