Android ViewPager Screen Rotation

匿名 (未验证) 提交于 2019-12-03 01:33:01

问题:

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?

回答1:

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


回答2:

Nothing solved, created an issue for AOSP:

http://code.google.com/p/android/issues/detail?can=2&start=0&num=100&q=&colspec=ID%20Type%20Status%20Owner%20Summary%20Stars&groupby=&sort=&id=54823



回答3:

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



标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!