嵌套viewpager的setCurrentItem

时间:2015-11-16 00:09:25

标签: android android-viewpager android-fragmentactivity screen-orientation

我有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 个答案:

答案 0 :(得分:3)

经过几个小时的审查,我提出了以下解决方案(这是我认为的一般方法)。我包括您已完成的步骤和其他必要步骤。

    1. 致电Here is a snippet:(您已经这样做了)
    1. 设置片段的保存状态。 (你已经这样做了)
    1. 在“主持人活动”上,调用以下内容以确保您的片段已保存在“活动”状态:

... (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 

这就是我所做的一切。希望这会有所帮助。