I'm using a ViewPager
together with a FragmentStatePagerAdapter
to host three different fragments:
- [Fragment1]
- [Fragment2]
- [Fragment3]
When I want to get Fragment1
from the ViewPager
in the FragmentActivity
.
What is the problem, and how do I fix it?
Another simple solution:
index
is the place of fragment in adapter like you addedfragment1
first so retreivefragment1
passindex
as 0 and so on for restFor my case, none of the above solutions worked.
However since I am using the Child Fragment Manager in a Fragment, the following was used:
Fragment f = getChildFragmentManager().getFragments().get(viewPager.getCurrentItem());
This will only work if your fragments in the Manager correspond to the viewpager item.
Hey I have answered this question here. Basically, you need to override
method of FragmentStatePagerAdapter.
Best solution is to use the extension we created at CodePath called SmartFragmentStatePagerAdapter. Following that guide, this makes retrieving fragments and the currently selected fragment from a ViewPager significantly easier. It also does a better job of managing the memory of the fragments embedded within the adapter.