Search code examples
androidandroid-fragmentsandroid-listviewandroid-viewpagerfragmentstatepageradapter

Android ViewPager + Fragments with dynamic ListViews


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 ViewPagerto 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).

  1. 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 FragmentStatePagerAdapterworks) but without restoring previous state of this fragment (e.g., ListViewshouldn'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 Fragmentstate, when it is created from scratch.

  2. Once again, let's say 3rd tab is selected. Then, when I go for example to the second tab, Fragmentfor this tab should be still in memory (that's fine, it's how FragmentStatePagerAdapterworks), but in this situation I want to decide if my ListViewdata should be updated (depending on some conditions). How can I notify this Fragment that it's selected?


Solution

  • 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.