简体   繁体   中英

Fragments in are not restored after orientation change

In my program, I have the following hierarchy:

Activity
    Fragment
        ViewPager + FragmentStatePagerAdapter
            Fragment containing video

The fragment that is nested immediately in the activity is initialized using setRetainInstance(true). This led to a crash whenever switching orientation. Used the solution described in the bug report: https://code.google.com/p/android/issues/detail?id=42601#c10 .

Still, the app would crash whenever I would switch orientation. I found another bug report + solution: https://code.google.com/p/android/issues/detail?id=42601#c32 .

After applying this solution I was able to rotate the device without the app crashing. However, the deeply nested fragment did not retain its state. As this fragment contains a video that should continue playing in spite of any orientation change, this is a must-have. I found a third bug report here describing this is a known issue in android support library versions 20 an up: https://code.google.com/p/android/issues/detail?id=74222#c17

Now, it does seem that the deepest fragment is retaining some kind of state. At least it is not destroyed, since the audio of the video keeps playing throughout and after the orientation change. However, the fragment is not restored after the orientation change. I simply see a white rectangle where the video should be.

As you can see, this is getting ridiculous. I have already had to use three hacky solutions to bugs in the ViewPager class, and it is still not working properly. If anybody has any idea what else I can try, I will be very much obliged.

Eventually, I did not find a solution to the problem. I have solved the problem by retaining the state of the nested fragments in the parent fragment, which does correctly retain state. To do this, I did the following:

  • Add a HashMap to the parent fragment
  • Gave every fragment a unique ID string that could be restored whenever the fragment was recreated
  • Created a state object for all nested fragments in their onCreate method and added it to the HashMap in the parent fragment. Or, if ((ParentFragment)getParentFragment()).stateMap.contains(id), restore the existing state.
  • Moved all member variables of the nested fragment to the StateObjects

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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