0

I have a fragment that contains a RecyclerView. When I return to the fragment from somewhere else, I do

if(null!=savedInstanceState) {
  mScrollPosition = savedInstanceState.getInt(ITEM_POSITION);
  mRecyclerView.scrollToPosition(mScrollPosition);
}

but now I don't know what to put inside onSaveInstanceState:

@Override
public void onSaveInstanceState(Bundle bundle){
    super.onSaveInstanceState(bundle);
    Log.d(TAG, "onSaveInstanceState");
    mScrollPosition=mRecyclerView.getScrollPosition();//???
    bundle.putInt(NITEM_POSITION,mScrollPosition);
}

There is no mRecyclerView.getScrollPosition().

update

after testing it turns out that using mRecyclerView.scrollToPosition is not fine enough to ensure a smooth user experience. In cases where the item views are tall enough, scrollToPosition(ofFirstVisibleItem) can be way off. So is there a finer solution to this?

learner
  • 11,490
  • 26
  • 97
  • 169

1 Answers1

1

You can get the scroll from the LayoutManager. For example:

 mScrollPosition = ((LinearLayoutManager) layoutManager).findFirstVisibleItemPosition();

also check this answer How to save RecyclerView's scroll position using RecyclerView.State?

Community
  • 1
  • 1
HellCat2405
  • 752
  • 7
  • 16
  • Although you sort of answered the question, it turns out the assumption was wrong. Using scrollToPosition does not actually return the view to where it left: if an item is tall enough, it is very apparent to the user that the position has shifted. So is there a better way to do this instead of using adapter position? – learner Oct 20 '15 at 13:45
  • many thanks. It looks exactly like what I need, but I am not sure where to put what. Sorry, but I am a at that level :). The code does not look like it goes in my fragment, for instance. And there are many parts. I know it's a bit much, but do you mind showing where to put what? I am sure other people here would be grateful as well. – learner Oct 20 '15 at 13:54
  • Sorry for a lot of link, don't have time for detailed answer http://emuneee.com/blog/2013/01/07/saving-fragment-states/ and http://stackoverflow.com/questions/15313598/once-for-all-how-to-correctly-save-instance-state-of-fragments-in-back-stack – HellCat2405 Oct 20 '15 at 13:58