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

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

喜欢的东西:

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

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

RecyclerView不支持滚动到绝对位置

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


当前回答

你只需要调用recyclerview. scrolltopposition (position)。这很好!

如果你想在适配器中调用它,只需让你的适配器拥有recyclerview的实例或包含recyclerview的活动或片段,然后在它们中实现getRecyclerview()方法。

我希望它能帮助你。

其他回答

我所做的恢复滚动位置后刷新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。

//滚动项目pos

linearLayoutManager.scrollToPositionWithOffset(pos, 0);

在我的情况下,我的RecyclerView有一个填充顶部像这样

<android.support.v7.widget.RecyclerView
     ...
     android:paddingTop="100dp"
     android:clipToPadding="false"
/>

然后滚动一个项目到顶部,我需要

recyclerViewLinearLayoutManager.scrollToPositionWithOffset(position, -yourRecyclerView.getPaddingTop());

这很简单

recyclerView.scrollToPosition(position)

我使用下面的代码将一个项目(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);

似乎能快速解决问题。