private int lastPosition = 0;
private int lastOffset = 0;
在initData 里加
//监听RecyclerView滚动状态
recyclerView.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) recyclerView.getLayoutManager();
//获取可视的第一个view
View topView = layoutManager.getChildAt(0);
if(topView != null) {
//获取与该view的顶部的偏移量
lastOffset = topView.getTop();
//得到该View的数组位置
lastPosition = layoutManager.getPosition(topView);
}
}
/*
* 让RecyclerView滚动到指定位置
*/
private void scrollToPosition() {
if(recyclerView.getLayoutManager() != null && lastPosition >= 0) {
((LinearLayoutManager) recyclerView.getLayoutManager()).scrollToPositionWithOffset(lastPosition, lastOffset);
}
}
在加载完数据后加 scrollToPosition();