android - RecyclerView smoothScroolToPositionFromTop()

标签 android android-recyclerview

是否有 ListView 的 smoothScrollToPositionFromTop() 的替代品?对于 RecyclerView?我正在尝试将 ListView 代码迁移到 RecyclerView,但我在任何地方都看不到它的 RecyclerView 版本。

有一种方法叫做 RecyclerView.smoothScrollToPosition() ,但是你不能定义相对于屏幕顶部元素的偏移量(我需要列表滚动到一个位置,并且总是在该位置是列表中的第一个可见子元素时停止)。

最佳答案

要始终将目标位置平滑滚动到顶部,您可以使用像这样的自定义 LinearLayoutManager:

public class CustomLinearLayoutManager extends LinearLayoutManager {
    private Context context;

    public CustomLinearLayoutManager(Context context) {
        super(context);
        this.context = context;
    }

    public CustomLinearLayoutManager(Context context, int orientation, boolean reverseLayout) {
        super(context, orientation, reverseLayout);
        this.context = context;
    }

    public CustomLinearLayoutManager(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
        super(context, attrs, defStyleAttr, defStyleRes);
        this.context = context;
    }

    @Override
    public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state, int position) {
        LinearSmoothScroller smoothScroller = new LinearSmoothScroller(context) {

            @Override
            public PointF computeScrollVectorForPosition(int targetPosition) {
                return CustomLinearLayoutManager.this.computeScrollVectorForPosition(targetPosition);
            }

            @Override
            protected int getVerticalSnapPreference() {
                return SNAP_TO_START;
            }
        };

        smoothScroller.setTargetPosition(position);
        startSmoothScroll(smoothScroller);
    }
}

关于android - RecyclerView smoothScroolToPositionFromTop(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31410884/

相关文章:

android - 通过代码获取昨天的日期

android - 回收站 View 不显示数据

java - Android Recyclerview - 增加所有内部 TextView 的字体大小

android - 每个项目都会调用 recyclerview 的查看者

Android高程 - 相同的值不同的阴影

android - 从浏览器打开我的 Android 应用程序的链接

java - Android Socket - 内存泄漏 - 传入消息

java - 从 Google map 获取坐标并将其插入 PostgreSQL

java - 改造不良请求和 RecyclerView : No adapter attached; skipping layout

java - activitythread.performlaunchactivity(activitythread$activityclientrecord intent) 找不到源