1

I'm looking at some demo code that shows how to use a Fragment Adapter (Tab Adapter in this case). I'm curious as to what exactly the instantiate() method does. I see it used in the following demo code on this page:

http://developer.android.com/reference/android/support/v4/view/ViewPager.html

(see the getItem() method within the TabsAdapter class)

If I'm reading the demo code correctly, every time a user clicks on one of the tabs, a new Fragment is created? And thus the fragment starts the entire life-cycle again (onAttach()...onCreate()... etc)? This sounds awfully inefficient. I would think that the fragment that will represent the content for each tab should be instantiated only once (perhaps in the addTab() method), and then saved into some collection where it can be fetched when getItem() is called.

Please correct me if I'm mistaken in any of this. I'm trying to better understand how to manage fragments.

Finer Recliner
  • 1,579
  • 1
  • 13
  • 21

2 Answers2

0

My money would be on that the setCurrentItem() function doesn't actually destroy the existing Fragment being shown in that tab. Otherwise there's really not much of a reason for the adapter to have a List of available tabs. Likely, when you switch from one tab to another, setCurrentItem() just detaches the UI from the currently active Fragment (or calls its onPause() method) and then re-attaches the UI for the newly selected Fragment (or calls its onResume() method).

But, if you're in doubt, you could read the source :)

Hope it helps, David

Agilanbu
  • 2,747
  • 2
  • 28
  • 33
David C. Sainte-Claire
  • 2,461
  • 1
  • 15
  • 12
0

I was able to find an explanation for my question here

Agilanbu
  • 2,747
  • 2
  • 28
  • 33
Finer Recliner
  • 1,579
  • 1
  • 13
  • 21