I have a ViewPager
nested in a fragment, and when the device changes orientation I'd like to save and restore which page the ViewPager
was on. I'm currently doing this:
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mViewPager = (ViewPager) inflater.inflate(R.layout.activity_albumpicker, container, false);
// Create the adapter that will return a fragment for each of the three
// primary sections of the activity.
mSectionsPagerAdapter = new SectionsPagerAdapter(getChildFragmentManager());
setRetainInstance(true);
// Set up the ViewPager with the sections adapter.
mViewPager.setAdapter(mSectionsPagerAdapter);
if(savedInstanceState != null) {
mViewPager.setCurrentItem(savedInstanceState.getInt("pagerState"), false);
}
return mViewPager;
}
@Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putInt("pagerState", mViewPager.getCurrentItem());
}
during onSaveInstanceState
the value being saved is correct, and in onCreateView
after rotating the value of savedInstanceState.getInt("pagerState")
is also correct. But nothing happens, the ViewPager
stays on its default page, and there's nothing in the logcat. I'm stumped.
After couple hours of reviewing some certain stuffs, I come up with the following solution (which is a general way to do I suppose). I include both steps You've done and other necessary steps.
setRetainInstance(true);
(You've done this)Here is a snippet:
That is all I do to make it works. Hope this helps.