0

How can I get a list of all child fragments that I have set up using a v4 viewpager with a FragmentPagerAdapter

The viewpager exists on the main activity

Alex K
  • 7,771
  • 9
  • 35
  • 54
dowjones123
  • 3,233
  • 5
  • 34
  • 72

1 Answers1

4

You can use the getCount() and getItem(int) methods to iterate through all the fragments in your FragmentPagerAdapter. For example:

List<Fragment> allFragments = new LinkedList<Fragment>();
for (int i = 0; i < adapter.getCount(); i++) {
     Fragment f = adapter.getItem(i);
     allFragments.add(f);
}

See the PagerAdapter and FragmentPagerAdapter classes for an explanation of how these methods work.

Mike Laren
  • 7,388
  • 17
  • 46
  • 67
  • Thansk @Mike. in the getItem(int i) method of the adapter, I am over-riding it to provide a new MyFragment_i(); for different i (to have 3 diff fragment for 3 diff tabs/swipes). So if I call getItem(i) again, won't it create a new fragment and return that instead of the existing fragment? – dowjones123 Jan 03 '15 at 03:21
  • 1
    That depends on your implementation. If `getItem()` always returns a new item them yes, but if it caches it in some map like a `HashMap` then a single instance is returned for each type of fragment. Also, if you use a collection to keep your fragments then you can just access the collection directly to retrieve the list of all child fragments (which is what you asked originally). – Mike Laren Jan 03 '15 at 03:27
  • I think I got it now. So in an implementation like http://developer.android.com/reference/android/support/v4/app/FragmentPagerAdapter.html , where getItem() returns a newInstance of a Fragment - I would assume that switching tabs after all 3 tabs have been viewed once does not call the getItem() method (if i set setOffscreenPageLimit(2))? – dowjones123 Jan 03 '15 at 03:31
  • 1
    I would assume that the behavior would be controlled by the consumer of the `FragmentPagerAdapter`. Either way, you can force it to always return the same fragment for a given index using the HashMap approach. `if (map.contains(i)) return map.get(i)`, otherwise create the fragment and add it to the map before returning. – Mike Laren Jan 03 '15 at 03:42