如何在Android中保存RecyclerView的滚动位置? [英] How to save scroll position of RecyclerView in Android?
问题描述
我有SwipeRefreshLayout内部的Recycler视图.另外,具有打开另一个活动中的每个项目的能力. 返回到回收站后,我需要滚动到所选项目或上一个Y. 该怎么做?
I have Recycler view which lays inside of SwipeRefreshLayout. Also, have ability to open each item in another activity. After returning back to Recycler I need scroll to chosen item, or to previous Y. How to do that?
是的,我搜寻了一下,在StackOverFlow中找到了有关保存布局管理器实例的文章,例如:
Yes, I googled, found articles in StackOverFlow about saving instance of layout manager, like this one: RecyclerView store / restore state between activities. But, it doesn't help me.
更新
现在我有这种解决问题的方法,但是,当然,它也行不通.
Right now I have this kind of resolving problem, but, of course, it also doesn't work.
private int scrollPosition;
...//onViewCreated - it is fragment
recyclerView.setHasFixedSize(true);
LinearLayoutManager llm = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(llm);
data = new ArrayList<>();
adapter.setData(getActivity(), data);
recyclerView.setAdapter(adapter);
...
@Override
public void onResume() {
super.onResume();
recyclerView.setScrollY(scrollPosition);
}
@Override
public void onPause() {
super.onPause();
scrollPosition = recyclerView.getScrollY();
}
是的,我已经尝试过scrollTo(int,int)-不起作用.
Yes, I have tried scrollTo(int, int) - doen't work.
现在我尝试仅滚动到例如Y = 100,但它根本不滚动.
Now I tried just scroll, for example, to Y = 100, but it doesn't scrolling at all.
推荐答案
通过@onPause保存回收视图位置的当前状态:
Save the current state of recycle view position @onPause:
positionIndex= llManager.findFirstVisibleItemPosition();
View startView = rv.getChildAt(0);
topView = (startView == null) ? 0 : (startView.getTop() - rv.getPaddingTop());
通过@onResume恢复滚动位置:
Restore the scroll position @onResume:
if (positionIndex!= -1) {
llManager.scrollToPositionWithOffset(positionIndex, topView);
}
或另一种方式可以是@onPause:
or another way can be @onPause:
long currentVisiblePosition = 0;
currentVisiblePosition = ((LinearLayoutManager)rv.getLayoutManager()).findFirstCompletelyVisibleItemPosition();
还原@onResume:
restore @onResume:
((LinearLayoutManager) rv.getLayoutManager()).scrollToPosition(currentVisiblePosition);
currentVisiblePosition = 0;
这篇关于如何在Android中保存RecyclerView的滚动位置?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!