嵌套viewpager的setCurrentItem

setCurrentItem of nested viewpager

我有一个嵌套在片段中的 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 中什么也没有。我被难住了。

经过几个小时的审查某些内容后,我提出了以下解决方案(我想这是一种通用的方法)。我包括您已完成的步骤和其他必要的步骤。

    1. 致电 setRetainInstance(true);(您已完成此操作)
    1. 设置片段的保存状态。 (你已经做到了)
    1. 在主机 Activity 上,调用以下命令以确保您的片段已保存在 Activity 的状态:

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();
   }
 }

这就是我所做的一切,让它发挥作用。希望这有帮助。