7

I have an Activity with ActionBarSherlock tabs and a ViewPager inside it. When the pages are scrolled, the tabs are switched and tabs are changed, the current page is changed too. I am using a class that extends FragmentStatePagerAdapter as adapter in the pageview. The problem is that when the device rotates, the getItem from the page adapter is not called and looks like the fragments references are not right. That's a huge problem, since the user must fulfill some fields inside the pager. These fields are recovered in correctly on the rotation, but since I the references for the fragments are not right, I can't save these values in right way. Any idea about the rotation?

3 Answers3

3

Save the current page number in onSavedInstanceState:

@Override
protected void onSaveInstanceState(Bundle outState) {
    super.onSaveInstanceState(outState);
    outState.putInt("item", mViewPager.getCurrentItem());
}

Then in onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState != null) {
         mViewPager.setCurrentItem(savedInstanceState.getInt("item"));
    }
}
Neoh
  • 15,906
  • 14
  • 66
  • 78
  • Hi, Neoh. Save the current page didn't work. When I rotate, the page after rotation is the same. The point is that the getItem from adapter is not called again, after the rotation. – davidtiagoconceicao Apr 30 '13 at 12:30
  • There is a mistake. Try use `mViewPager.setCurrentItem(savedInstanceState.getInt("item"))` instead. – Neoh Apr 30 '13 at 12:32
  • 1
    Hi Neoh, That's what I did: outState.putInt(CURRENT_PAGER_ITEM, currentItem); and then pager.setCurrentItem(savedInstanceState.getInt(CURRENT_PAGER_ITEM)); on the onCreate. Thanks for helping. – davidtiagoconceicao Apr 30 '13 at 12:39
0

I've posted a solution to this problem in the question here https://stackoverflow.com/a/21517213/3170538. Essentially you want to be subclassing PagerAdapter, not FragmentPagerAdapter, and handling the creating and deleting of items yourself (getItem() is a routine that is called from FragmentPagerAdapter.instantiateItem(), so the issue is when the screen is rotated the routine doesn't re-call getItem(), because of some presumably performance-enhancing code. When you subclass it you can handle the rotating properly by not trying to reconnect to the deleted fragment).

Community
  • 1
  • 1
Josh Hunt
  • 620
  • 7
  • 10