问题
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.
回答1:
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.
- Call
setRetainInstance(true);
(You've done this)
- Call
- Setup Fragment's saving states. (You've done this)
- On Host Activity, call the following to make sure your Fragment has been saved in Activity's state:
Here is a snippet:
... (other stuffs)
Fragment mainFragment; // define a local member
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// After you rotate your screen, by default your Activity will be recreated
// with a bundle of saved states, i.e at this point, savedInstanceState is
// not null in general. If you debug it, you could see how it saved your
// latest FragmentTransactionState, which hold your Fragment's instance
// For safety, we check it here, and retrieve the fragment instance.
mainFragment = getSupportFragmentManager().findFragmentById(android.R.id.content);
if (mainFragment == null) {
// in very first creation, your fragment is null obviously, so we need to
// create it and add it to the transaction. But after the rotation, its
// instance is nicely saved by host Activity, so you don't need to do
// anything.
mainFragment = new MainFragment();
getSupportFragmentManager().beginTransaction()
.replace(android.R.id.content, mainFragment)
.commit();
}
}
That is all I do to make it works. Hope this helps.
来源:https://stackoverflow.com/questions/33726697/setcurrentitem-of-nested-viewpager