问题描述
我在寻找一种方式来滚动 RecyclerView
显示在上面选择的项目。
I'm looking for a way to scroll a RecyclerView
to show the selected item on top.
在列表视图
我是能够做到这一点使用 scrollTo(X,Y)
并获得顶部需要被居中的元素
In a listview
I was able to do that by using scrollTo(x,y)
and getting the top of the element that need to be centered.
是这样的:
@Override
public void onItemClick(View v, int pos){
mylistView.scrollTo(0, v.getTop());
}
的问题是,当RecyclerView使用它的方法scrollTo说返回错误
The problem is that the RecyclerView returns an error when using it's scrollTo method saying
recyclerview不支持滚动到一个绝对位置
我怎么能滚动RecyclerView把所选项目的视图的顶部?
How can I scroll a RecyclerView to put the selected item at the top of the view?
推荐答案
如果您使用的是LinearLayoutManager或StaggeredGridLayoutManager,他们每个人都有一个scrollToPositionWithOffset方法既需要的位置,并从RecyclerView,这似乎是它的启动项目的启动也偏移将完成你所需要的(设置偏移量为0应与顶部对齐)。
If you are using the LinearLayoutManager or StaggeredGridLayoutManager, they each have a scrollToPositionWithOffset method that takes both the position and also the offset of the start of the item from the start of the RecyclerView, which seems like it would accomplish what you need (setting the offset to 0 should align with the top).
例如:
//Scroll item 2 to 20 pixels from the top
linearLayoutManager.scrollToPositionWithOffset(2, 20);
这篇关于滚动RecyclerView显示在上面选中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!