0

I've seen this question answered with regards to an activity here save scroll position in an activity

The above solution uses onSaveInstanceState() for an activity. But this is proving unfruitful for me with onSaveInstanceState() for a fragment. I'm using a ViewPagerwith fragments.

flutter
  • 6,188
  • 9
  • 45
  • 78
  • You can use a static class like [THIS](https://stackoverflow.com/questions/7486012/static-classes-in-java) for save your data. – G. Ciardini Jun 08 '18 at 10:33

2 Answers2

0

I am assuming you are using recyclerView inside fragment. To retain your scrolled position here what you should do:

  1. Declare one static variable in your Activity ex. public static int currentVisiblePosition = 0; and declare layoutManager in your fragment RecyclerView.LayoutManager layoutManager;

  2. In OnPause() of your fragment write

     @Override
        public void onPause() {
            super.onPause();
            try{
                MainActivity.currentVisiblePosition = ((LinearLayoutManager)layoutManager).findFirstCompletelyVisibleItemPosition();
            }
            catch (NullPointerException ne)
            {
                ne.printStackTrace();
            }
        }
    
  3. When you are pressing the back button and wants to show the last shown item of recyclerView to a user here what you should do, add following code where you are loading the list

        if(MainActivity.currentVisiblePosition > 0)
                        {
                            ((LinearLayoutManager) layoutManager).scrollToPosition((int) MainActivity.currentVisiblePosition);
                            MainActivity.currentVisiblePosition = 0;
                        }
    

this will show item which was there before moving to next activity or fragment.

Thanks for reading... Happy Coding...!!!

0

An options you can use is to retain the instance of your fragment by setting in your fragment's onCreate() the following:

setRetainInstance(true)

This means that this fragment will retain its instance and all the variable values that are assigned to it. This allows you to use those values without recurring to onSavedInstance. So basically here what you need to do is to store the current position in a variable.

Be aware that, since you are retaining an instance you should be careful to verify when you create new instances so you don't end up with multiple instances if you don't wish to.

Ricardo
  • 9,136
  • 3
  • 29
  • 35