I have an Activity
with ViewPager
and three Fragments
with-in. One Fragment
contains ListView
with custom CursorAdapter
which loads data from database.
I've noticed that my cursor adapter loads data every time I switch Fragments
in ViewPager
. I think that it's normal and is due to the fact that every Fragment
has its own lifecycle.
Regarding this it will be great pleasure for me if the users of the stackoverflow explain about their experience or best practices at all.
Thanks!
ViewPagers
maintain the state of only certain number of fragments, which defaults to 1 for both sides of the current selected fragment. For example, if you have 3 fragments, when the first is selected, only first two fragments will be instantiated and have the listview data loaded. Alternatively, if you have the second fragment selected, the first and the third will be instantiated. If you switch to the third fragment, the second fragment will be retained, but the first one will be lost. However, you can set the number of fragments to be retained with calling setOffscreenPageLimit
method on viewPager
with any number of fragments to retain you need. Though you should remember, that setting the number too high may cause your app to consume too much memory.
For example, if you want your fragment to not reload listview content from db while switching fragments and you have 3 framents in your viewPager
, you may write the following code:
ViewPager mViewPager;
mViewPager.setOffscreenPageLimit(2);