当前位置: 移动技术网 > 移动技术>移动开发>Android > Android RecyclerView如何获得当前滑动的位置?

Android RecyclerView如何获得当前滑动的位置?

2018年02月22日  | 移动技术网移动技术  | 我要评论

Android本身并没有提供直接获得RecyclerView具体位置的api,layoutManager.findFirstCompletelyVisibleItemPosition(); 只是获得第一个可见的,

因为layoutManager.scrollToPositionWithOffset() 参数有一个是offset,这个值,Android没有直接提供,

在了安卓源码之后(基于android 6.0)总结出了下面的方案可以获得获得RecyclerView滑动的位置,目前在5.0和6.0上测试时OK的,在7.0未测试

这种使用场景并不多,一般activity或者fragment都会有系统记录状态位置,但是例如文件管理器,返回上一级目录没有必要使用多个fragment或者activity,

那么记录最后的位置就显得尤为重要了

//获得RecyclerView滑动的位置

private int[] getRecyclerViewLastPosition(LinearLayoutManager layoutManager) {

int[] pos = new int[2];

pos[0] = layoutManager.findFirstCompletelyVisibleItemPosition();

OrientationHelper orientationHelper = OrientationHelper.createOrientationHelper(layoutManager, OrientationHelper.VERTICAL);

int fromIndex = 0;

int toIndex = itemBeanList.size();

final int start = orientationHelper.getStartAfterPadding();

final int end = orientationHelper.getEndAfterPadding();

final int next = toIndex > fromIndex 1 : -1;

for (int i = fromIndex; i != toIndex; i += next) {

final View child = mRv.getChildAt(i);

final int childStart = orientationHelper.getDecoratedStart(child);

final int childEnd = orientationHelper.getDecoratedEnd(child);

if (childStart < end && childEnd > start) {

if (childStart >= start && childEnd <= end) {

pos[1] = childStart;

LogUtils.v("position = " + pos[0] + " off = " + pos[1]);

return pos;

}

}

}

return pos;

}

//重新设置RecyclerView的位置

int []pos = getRecyclerViewLastPosition(layoutManager);

layoutManager.scrollToPositionWithOffset(pos[0],pos[1]);

//记得刷新下数据

Adapter.notifyDataSetChanged()

如对本文有疑问, 点击进行留言回复!!

相关文章:

验证码:
移动技术网