我正在寻找一种方法来滚动RecyclerView,以显示选中的项目在顶部。
在一个ListView中,我能够通过使用scrollTo(x,y)来做到这一点,并获得需要居中的元素的顶部。
喜欢的东西:
@Override
public void onItemClick(View v, int pos){
mylistView.scrollTo(0, v.getTop());
}
问题是RecyclerView在使用它的scrollTo方法时返回一个错误说
RecyclerView不支持滚动到绝对位置
我如何滚动一个RecyclerView把选定的项目放在视图的顶部?
试试对我有效的方法,酷!
创建一个私有静态变量int displayedposition = 0;
现在你的RecyclerView在你的活动中的位置。
myRecyclerView.setOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
}
@Override
public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
super.onScrolled(recyclerView, dx, dy);
LinearLayoutManager llm = (LinearLayoutManager) myRecyclerView.getLayoutManager();
displayedposition = llm.findFirstVisibleItemPosition();
}
});
将此语句放置在视图中显示前站点的位置。
LinearLayoutManager llm = (LinearLayoutManager) mRecyclerView.getLayoutManager();
llm.scrollToPositionWithOffset(displayedposition , youList.size());
好吧,就是这样,它对我来说很好
调速器也一样
public class SmoothScrollLinearLayoutManager extends LinearLayoutManager {
private static final float MILLISECONDS_PER_INCH = 110f;
private Context mContext;
public SmoothScrollLinearLayoutManager(Context context,int orientation, boolean reverseLayout) {
super(context,orientation,reverseLayout);
mContext = context;
}
@Override
public void smoothScrollToPosition(RecyclerView recyclerView, RecyclerView.State state,
int position) {
RecyclerView.SmoothScroller smoothScroller = new TopSnappedSmoothScroller(recyclerView.getContext()){
//This controls the direction in which smoothScroll looks for your view
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return new PointF(0, 1);
}
//This returns the milliseconds it takes to scroll one pixel.
@Override
protected float calculateSpeedPerPixel(DisplayMetrics displayMetrics) {
return MILLISECONDS_PER_INCH / displayMetrics.densityDpi;
}
};
smoothScroller.setTargetPosition(position);
startSmoothScroll(smoothScroller);
}
private class TopSnappedSmoothScroller extends LinearSmoothScroller {
public TopSnappedSmoothScroller(Context context) {
super(context);
}
@Override
public PointF computeScrollVectorForPosition(int targetPosition) {
return SmoothScrollLinearLayoutManager.this
.computeScrollVectorForPosition(targetPosition);
}
@Override
protected int getVerticalSnapPreference() {
return SNAP_TO_START;
}
}
}
如果你想自动滚动而不显示滚动运动,那么你需要写以下代码:
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);