我有ViewPager
嵌套在片段中,当设备更改方向时,我想保存并恢复ViewPager
所在的页面。我目前正在这样做:
@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());
}
在onSaveInstanceState
期间保存的值是正确的,并且在onCreateView
中旋转savedInstanceState.getInt("pagerState")
的值也是正确的。但没有任何反应,ViewPager
保留在其默认页面上,并且logcat中没有任何内容。我很难过。
答案 0 :(得分:3)
经过几个小时的审查,我提出了以下解决方案(这是我认为的一般方法)。我包括您已完成的步骤和其他必要步骤。
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();
}
}
A B C
2 1 4
3 4 5
3 1 1
1 4 0
5 0 1
这就是我所做的一切。希望这会有所帮助。