Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android ViewPager Screen Rotation

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?

like image 821
davidtiagoconceicao Avatar asked Apr 30 '13 12:04

davidtiagoconceicao


1 Answers

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"));
    }
}
like image 135
Neoh Avatar answered Nov 15 '22 01:11

Neoh