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?
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.
UPDATE
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();
}
Yes, I have tried scrollTo(int, int) - doen't work.
Now I tried just scroll, for example, to Y = 100, but it doesn't scrolling at all.
to save position to Preferences, add this to your onStop()
then restore position like this
this last code should be added inside an event of the Adapter (not sure witch event but in my case was onEvent() - com.google.firebase.firestore.EventListener)
User your recycler view linearlayoutmanager for getting scroll position
and when restoring use following code
Hope this helps you
A lot of these answers seem to be over complicating it.
The LayoutManager supports
onRestoreInstanceState
out of the box so there is no need to save scroll positions etc. The built in method already saves pixel perfect positions.example fragment code (null checking etc removed for clarity):
then just call
once your data has been reattached to your
RecyclerView
Save the current state of recycle view position @onPause:
Restore the scroll position @onResume:
or another way can be @onPause:
restore @onResume:
You can use
scrollToPosition
orsmoothScrollToPosition
to scroll to any item position in RecyclerView.If you want to scroll to item position in adapter, then you would have to use adapter's
scrollToPosition
orsmoothScrollToPosition
.