简体   繁体   中英

Restoring a fragment using FragmentPagerAdapter

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.

Add

setRetainInstance(true);

in onCreateView method of a Fragment

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.

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