mRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
@Override
public void onScrollStateChanged(RecyclerView recyclerView, int newState) {
super.onScrollStateChanged(recyclerView, newState);
if(recyclerView.getLayoutManager() != null) {
getPositionAndOffset();
}
}
});
/**
* 记录RecyclerView当前位置
*/
private void getPositionAndOffset() {
LinearLayoutManager layoutManager = (LinearLayoutManager) mRecyclerView.getLayoutManager();
View topView = layoutManager.getChildAt(0);
if(topView != null) {
lastOffset = topView.getTop();
lastPosition = layoutManager.getPosition(topView);
}
}
/**
* 让RecyclerView滚动到指定位置
*/
private void scrollToPosition() {
if(mRecyclerView.getLayoutManager() != null && lastPosition >= 0) {
((LinearLayoutManager) mRecyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
}
}