简体   繁体   English

Android ViewPager屏幕旋转

[英]Android ViewPager Screen Rotation

I have an Activity with ActionBarSherlock tabs and a ViewPager inside it. 我有一个带有ActionBarSherlock选项卡的Activity和一个ViewPager。 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. 我正在使用一个扩展FragmentStatePagerAdapter的类作为页面视图中的适配器。 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. 问题是当设备旋转时,不会调用页面适配器中的getItem,看起来片段引用不正确。 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? 关于轮换的任何想法?

Save the current page number in onSavedInstanceState: 将当前页码保存在onSavedInstanceState中:

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

Then in onCreate: 然后在onCreate:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState != null) {
         mViewPager.setCurrentItem(savedInstanceState.getInt("item"));
    }
}

I've posted a solution to this problem in the question here https://stackoverflow.com/a/21517213/3170538 . 我在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). 基本上你想要继承PagerAdapter,而不是FragmentPagerAdapter,并自己处理项目的创建和删除(getItem()是一个从FragmentPagerAdapter.instantiateItem()调用的例程,所以问题是当屏幕旋转时,例程没有'重新调用getItem(),因为一些可能是性能增强的代码。当你继承它时,你可以通过不尝试重新连接到已删除的片段来正确处理旋转。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM