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