滚动RecyclerView显示在上面选中的项目 [英] Scroll RecyclerView to show selected item on top

查看:2017
本文介绍了滚动RecyclerView显示在上面选中的项目的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在寻找一种方式来滚动 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 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或StaggeredGridLayoutManager,他们每个人都有一个<一个href="https://developer.android.com/reference/android/support/v7/widget/LinearLayoutManager.html#scrollToPositionWithOffset(int,%20int)">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显示在上面选中的项目的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆