RecyclerView scrollToPosition() 将项目放在底部。我怎样才能让它达到TOP?

RecyclerView scrollToPosition() puts the item on BOTTOM. How do I get it to TOP?

我有一个显示垂直字符串列表的 RecyclerView

Row0
Row1
Row2
Row3
Row4
...

我正在使用函数 recyclerView.scrollToPosition(position); 跳转到一行。但是,我要跳转到的行最终位于视图的底部!

例如,如果我 recyclerView.scrollToPosition(17); 我得到:

Row13
Row14
Row15
Row16
Row17  <--- 17 is at bottom (last visible row)

我想要的是:

Row17  <-- 17 to be on top (first visible row)
Row18
Row19
Row20
Row21 

我怎样才能做到这一点?

.scrollToPosition() 的默认行为是在滚动到的行显示在屏幕上后停止滚动。您可以使用具有固定偏移量的 scrollToPositionWithOffset(),以便它总计为滚动值。

LinearLayoutManager layoutManager = (LinearLayoutManager) recyclerView.getLayoutManager();
if (layoutManager != null) {
    layoutManager.scrollToPositionWithOffset(position, 20);
}

更新

how can I compute the offset value? Each row in my RecyclerView has a different height. Also I don't see how to measure it.

现在您可以计算屏幕上第一个和最后一个可见项目之间的差异,并且仅当屏幕上最后一个可见项目是您要首先推送到的当前项目时才有效。

layoutManager.scrollToPosition(position));

int firstItemPosition = ((LinearLayoutManager) recyclerview.getLayoutManager())
            .findFirstCompletelyVisibleItemPosition();

int lastItemPosition = ((LinearLayoutManager) recyclerview.getLayoutManager())
            .findLastCompletelyVisibleItemPosition();

layoutManager.scrollToPositionWithOffset(position, 
            Math.abs(lastItemPosition - firstItemPosition));