How to handle fragments saving state within ViewPager that's inside a NavigationDrawer fragment?
Asked Answered
H

0

1

Background

I have the next scenario:

  1. There is a navigation drawer with items. each switches to a different fragment.
  2. One of the fragments holds a viewPager, which holds fragments.
  3. Each of the viewPager's fragments have a ListView in it.
  4. When the user switches between the pages of the viewPager, or goes to another navigation-drawer fragment, and then back to one of the viewPager's fragment, the ListView should be restored to its original state.

All that I've used is via the support library.

The problem

It seems that this situation doesn't work well with the support library, and I get various exceptions, for example :

 NullPointerException: Attempt to invoke virtual method 'int java.util.ArrayList.size()' on a null object reference viewpager

What I've found

I've found out that this issue is known (link here) .

What I've done (and it works) is this:

  1. the fragment with the viewPager holds all of the fragments instances.
  2. each fragment in the viewpager holds its inflated view and returns it in case onCreateView is called.
  3. each fragment in the viewpager saves&restores its saved-state like on normal fragments.
  4. the adapter I use for the viewPager extends from "FragmentStatePagerAdapter" , and it has a function "restoreState" that it overrides which won't call "super.restoreState()" .
  5. the activity that switches between the fragments holds a reference to the fragment with the viewPager.

This is quite wasteful (storing the reference to fragments and views), but it works.

The question

Is there any better solution than that?

Harms answered 25/12, 2014 at 15:33 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.