我正在寻找一种方法来滚动RecyclerView,以显示选中的项目在顶部。

在一个ListView中,我能够通过使用scrollTo(x,y)来做到这一点,并获得需要居中的元素的顶部。

喜欢的东西:

@Override
public void onItemClick(View v, int pos){
    mylistView.scrollTo(0, v.getTop());
}

问题是RecyclerView在使用它的scrollTo方法时返回一个错误说

RecyclerView不支持滚动到绝对位置

我如何滚动一个RecyclerView把选定的项目放在视图的顶部?


当前回答

我使用下面的代码将一个项目(thisView)平滑滚动到顶部。 它也适用于GridLayoutManager不同高度的视图:

View firstView = mRecyclerView.getChildAt(0);
int toY = firstView.getTop();
int firstPosition = mRecyclerView.getChildAdapterPosition(firstView);
View thisView = mRecyclerView.getChildAt(thisPosition - firstPosition);
int fromY = thisView.getTop();

mRecyclerView.smoothScrollBy(0, fromY - toY);

似乎能快速解决问题。

其他回答

特定位置滚动 这对我帮助很大。 通过单击listener,您可以获得适配器中的位置

layoutmanager.scrollToPosition(int position);

//滚动项目pos

linearLayoutManager.scrollToPositionWithOffset(pos, 0);

我不知道为什么我没有找到最好的答案,但这真的很简单。

recyclerView.smoothScrollToPosition(position);

没有错误

创建动画

请注意,如果scrolltopposition不工作,请注意您的RecyclerView是在一个NestedScrollView;参考这篇文章

如果你正在使用LinearLayoutManager或交错的GridLayoutManager,它们都有一个scrollToPositionWithOffset方法,该方法既取位置,也取项目从RecyclerView开始的偏移量,这似乎可以完成你所需要的(将偏移量设置为0应该与顶部对齐)。

例如:

//Scroll item 2 to 20 pixels from the top
linearLayoutManager.scrollToPositionWithOffset(2, 20);