I have a fragment with ViewPager having WebViews. When i rotate the phone the ViewPager shows the first page. This is because the activity and the fragment is created again. How do i save the state of ViewPager. The following code does not work
@Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
if (savedInstanceState != null)
{
// Restore last state for checked position.
int pos = savedInstanceState.getInt("currentPosition");
this.setSelectedItem(pos);
}
}
@Override
public void onSaveInstanceState(Bundle outSt开发者_JS百科ate)
{
super.onSaveInstanceState(outState);
outState.putInt("currentPosition", positionOfSelectedIndex);
}
In the constructor of your fragment put the following:
setRetainInstance(true);
If you have multiple constructors you will need to make sure this is in the default no-args constructor and then make sure each other constructor calls
this();
Then in your FragmentActivity that instantiates your PageAdapter put the following lines:
myPager = (ViewPager)findViewById(R.id.pager);
myAdapter = new MyPagerAdapter(anyParamsYouMightHave);
myPager.setAdapter(myAdapter);
myPageAdpater.setCurrentItem(indexOfSomePointYouWishToReturnTo);
Mark
It's all about how you create your FragmentActivity (host activity). It seems you can't save viewpager's state but you can save state of fragments you push to viewpager's adapter. Also you could save some data inside fragment (the same way). Also if you don't want adapter to destroy views automatically (when you swipe viewpager), override adapter's destroy method with no super there. See my question with code and simple solution: ViewPager and fragments — what's the right way to store fragment's state?
精彩评论