RecyclerView精确恢复到上次的位置

来源:互联网 发布:徐克版笑傲江湖 知乎 编辑:程序博客网 时间:2024/05/17 22:51

在项目开发中,我们可能遇到这样的需求:跳转到另一个界面,但是需要记录RecyclerView在之前的位置,以方便跳转回来的时候界面不变化。比如ES文件浏览器。

代码如下

定义两个成员变量:    private int lastPosition = 0;    private int lastOffset = 0;记录位置,OnScrollListener,onScrollStateChanged()里添加:                    View topView = mLayoutManager.getChildAt(0);          //获取可视的第一个view                    lastOffset = topView.getTop();                                   //获取与该view的顶部的偏移量                    lastPosition = mLayoutManager.getPosition(topView);  //得到该View的数组位置   恢复位置:                //mLayoutManager.scrollToPosition(lastPosition);                //这样更精确                ((LinearLayoutManager)mLayoutManager).scrollToPositionWithOffset(lastPosition, lastOffset);
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • 7
  • 8
  • 9
  • 10
  • 11
  • 12
  • 13
1