滚动 RecyclerView 以在顶部显示所选项目 [英] Scroll RecyclerView to show selected item on top
问题描述
我正在寻找一种滚动 RecyclerView
以在顶部显示所选项目的方法.
I'm looking for a way to scroll a RecyclerView
to show the selected item on top.
在 ListView
中,我可以通过使用 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 does not support scrolling to an absolute position
如何滚动 RecyclerView
以将所选项目置于视图顶部?
How can I scroll a RecyclerView
to put the selected item at the top of the view?
推荐答案
如果您使用的是 LinearLayoutManager
或 Staggered GridLayoutManager
,它们每个都有一个 scrollToPositionWithOffset 方法同时采用位置和还有从 RecyclerView
开始的项目开始的偏移量,这似乎可以完成你所需要的(将偏移量设置为 0 应该与顶部对齐).
If you are using the LinearLayoutManager
or Staggered GridLayoutManager
, 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 以在顶部显示所选项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!