4

I'm trying to save a current state of the ViewPager (current position etc.) by implementing two methods in its PagerAdapter: restoreState() and saveState(). However they seem to not work correctly in my case. What I'm doing wrong?

@Override
public Parcelable saveState() {

Bundle bundle = new Bundle();
bundle.putParcelable("instanceState", super.saveState());
bundle.putInt("stateToSave", position);
return bundle;
}

@Override
public void restoreState(Parcelable state, ClassLoader c) {
if (state instanceof Bundle) {
  Bundle bundle = (Bundle) state;
  position = bundle.getInt("stateToSave");
  super.restoreState(bundle.getParcelable("instanceState"), c);
  return;
}
super.restoreState(state, c);
}
biegleux
  • 13,179
  • 11
  • 45
  • 52
Marcin S.
  • 11,161
  • 6
  • 50
  • 63

1 Answers1

-1

Did you try to use onSaveInstanceState method from ViewPager? In your Activity/Fragment you can save state of ViewPager by calling this method and pass the result to Bundle.

After rebuilding the Activity/Fragment call onRestoreInstanceState(Parcelable p) using

Rudy Rudolf
  • 227
  • 2
  • 3
  • You should not be calling onSaveInstanceState and onRestoreInstanceState yourself. Leave it to the Android framework to do so. – Rajan Prasad Nov 24 '17 at 22:00