0

I have an application using two tabs, both containing fragments. I am using the FragmentPagerAdapter to manage tab changes. All works fine with two tabs.

I recently added a third tab and am having a bit of trouble. tab1(fragment1) is a LinearLayout of small fragments. tab2(fragment2) is a simple layout of text. tab3(fragment3) is also a simple layout of text.

If I switch between tab1 and tab2 both work properly and retain their states. However, if I switch between tab1 and tab3, tab3 shows the text properly but tab1 shows a blank tab.

I know that if a tab goes more than 1 position off the current position the fragment will be destroyed and the fragment will need to be recreated. Does FragmentPagerAdapter not do this automatically?

I discovered that if I rotate the device (with tab1 selected), the tab1 fragment will be restored with its correct state so the fragment is not being destroyed. It seems like there is an issue with the layout not being correctly recreated by the ViewPager but this is only a guess.

As a work around I set myViewPager.setOffscreenPageLimit(2) and the layout is retained. I would like to get this to work as I think its supposed to without forcing the fragments to stay in memory.

Scott Naef
  • 165
  • 3
  • 9

2 Answers2

0

Add

setRetainInstance(true);

in onCreateView method of a Fragment

ravindra.kamble
  • 1,023
  • 3
  • 11
  • 20
0

Reading docs for setOffScreenPageLimit(), makes me think your approach is fine. Look at this:

If you have a small number of pages (3-4) that you can keep active all at once, less time will be spent in layout for newly created view subtrees as the user pages back and forth.

You should keep this limit low, especially if your pages have complex layouts.

I'm curious though if setRetainInstance(true) will work, since it's the Adapter who decides to recreate a fragment not that it's get recreated during some Android change config operation.

Max Ch
  • 1,247
  • 10
  • 13
  • I already have setRetainInstance(true) on the tab1 fragment, but I'm thinking that I may not have it set on the fragments that are embedded inside of the tab fragment. The main fragment is indeed there, the menu items for that tab get created properly, its just that the layout is not rendered. I need to dig deeper with the layout inspector. – Scott Naef Jan 20 '14 at 16:19
  • I have checked and I have 'setRetainInsance' set on both the tabs fragment and its nested children. I have an 'add' functions of that tab and if I use it the new child fragment does get created. It seems to be a problem related to the child fragments being restored properly. Need to do more digging – Scott Naef Jan 20 '14 at 16:46