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

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

喜欢的东西:

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

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

RecyclerView不支持滚动到绝对位置

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


当前回答

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

例如:

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

其他回答

我所做的恢复滚动位置后刷新RecyclerView按钮点击:

if (linearLayoutManager != null) {

    index = linearLayoutManager.findFirstVisibleItemPosition();
    View v = linearLayoutManager.getChildAt(0);
    top = (v == null) ? 0 : (v.getTop() - linearLayoutManager.getPaddingTop());
    Log.d("TAG", "visible position " + " " + index);
}

else{
    index = 0;
}

linearLayoutManager = new LinearLayoutManager(getApplicationContext());
linearLayoutManager.scrollToPositionWithOffset(index, top);

在创建linearLayoutManager对象之前,从顶部获得第一个可见项的偏移量,并在实例化它之后,调用linearLayoutManager对象的scrollToPositionWithOffset。

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

例如:

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

如果你想自动滚动而不显示滚动运动,那么你需要写以下代码:

mRecyclerView.getLayoutManager().scrollToPosition(position);

如果你想显示滚动运动,那么你需要添加以下代码。 步骤1:你需要声明SmoothScroller。

RecyclerView.SmoothScroller smoothScroller = new
                LinearSmoothScroller(this.getApplicationContext()) {
                    @Override
                    protected int getVerticalSnapPreference() {
                        return LinearSmoothScroller.SNAP_TO_START;
                    }
                };

=>步骤2:你需要添加这段代码任何事件,你想要执行滚动到特定的位置。 首先你需要设置目标位置为平滑滚动。

smoothScroller.setTargetPosition(position);

然后你需要将SmoothScroller设置为LayoutManager。

mRecyclerView.getLayoutManager().startSmoothScroll(smoothScroller);

这很简单

recyclerView.scrollToPosition(position)

//滚动项目pos

linearLayoutManager.scrollToPositionWithOffset(pos, 0);