FragmentStatePagerAdapter vs FragmentPagerAdapter

There is another PagerAdapter type that you can use called FragmentPagerAdapter. FragmentPagerAdapter is used exactly like FragmentStatePagerAdapter. It only differs in how it unloads your fragments when they are no longer needed.

With FragmentStatePagerAdapter, your unneeded fragment is destroyed (Figure 11.4). A transaction is committed to completely remove the fragment from your activity’s FragmentManager. The “state” in FragmentStatePagerAdapter comes from the fact that it will save out your fragment’s Bundle from onSaveInstanceState(Bundle) when it is destroyed. When the user navigates back, the new fragment will be restored using that instance state.

Figure 11.4  FragmentStatePagerAdapter’s fragment management

Figure shows FragmentPagerAdapter’s fragment management.

FragmentPagerAdapter handles things differently. When your fragment is no longer needed, FragmentPagerAdapter calls detach(Fragment) on the transaction, instead of remove(Fragment). This destroys the fragment’s view, but leaves the fragment instance alive in the FragmentManager. So the fragments created by FragmentPagerAdapter are never destroyed (Figure 11.5).

Figure 11.5  FragmentPagerAdapter’s fragment management

Figure shows FragmentPagerAdapter’s fragment management.

Which kind of adapter you should use depends on your application. FragmentStatePagerAdapter is generally more frugal with memory. CriminalIntent is displaying what could be a long list of crimes, each of which will eventually include a photo. You do not want to keep all that information in memory, so you use FragmentStatePagerAdapter.

On the other hand, if your interface has a small, fixed number of fragments, FragmentPagerAdapter would be safe and appropriate. The most common example of this scenario is a tabbed interface. Some detail views have enough details to require two screens, so the details are split across multiple tabs. Adding a swipeable ViewPager to this interface makes the app tactile. Keeping these fragments in memory can make your controller code easier to manage. Plus, because this style of interface usually has only two or three fragments per activity, there is little danger of running low on memory.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.22.51.241