在项目开发中,我们可能遇到这样的需求:跳转到另一个界面,但是需要记录RecyclerView在之前的位置,以方便跳转回来的时候界面不变化。比如ES文件浏览器。
代码如下
1. 定义两个成员变量:
private int lastPosition = 0;//位置
private int lastOffset = 0;//偏移量
2.记录位置 OnScrollListener,onScrollStateChanged()里添加:
View topView = mLayoutManager.getChildAt(0); //获取可视的第一个view
lastOffset = topView.getTop(); //获取与该view的顶部的偏移量
lastPosition = mLayoutManager.getPosition(topView); //得到该View的数组位置
3.恢复位置:
((LinearLayoutManager)mLayoutManager).scrollToPositionWithOffset(lastPosition, lastOffset);