In my app I have activity with tabs (let's say 10 tabs). Each tab page contains Fragment
with ListView
(data displayed in this ListView is loaded dynamically from my server). I use ViewPager
to display these pages. I don't want to keep all the Fragments
in memory, so I decided to use FragmentStatePagerAdapter
(My adapter class extends these class).
Let's say 3rd tab is selected. Then, when I go for example to the first tab, Fragment
for this tab should be created from scratch (that's fine, it's how FragmentStatePagerAdapter
works) but without restoring previous state of this fragment (e.g., ListView
shouldn't be scrolled to the position saved when this Fragment
was last accessed - now it is scrolled).
So my first question is: how can I achieve such a behaviour? In other words, I want my adapter not to restore Fragment
state, when it is created from scratch.
Once again, let's say 3rd tab is selected. Then, when I go for example to the second tab, Fragment
for this tab should be still in memory (that's fine, it's how FragmentStatePagerAdapter
works), but in this situation I want to decide if my ListView
data should be updated (depending on some conditions). How can I notify this Fragment
that it's selected?
For #1, take a look at this blog post. They talk about fixing FragmentStatePagerAdpater to handle the case where the fragment class for an index changes, which isn't exactly what you want. However, it shows in detail how state is saved/restored and you should be able to figure out how to prevent it from there.
For #2, implement OnPageChangeListener in the Fragment that holds the ViewPager. Then use this to get the current fragment when it changes so you can call some public method on it, telling it to update.