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?
This is based on Steven's answer above. This will return actual instance of the fragment which is already attached to the parent activity.
Ok for the adapter
FragmentStatePagerAdapter
I fund a solution :in your FragmentActivity :
and create a methode in your class FragmentActivity - So that method give you access to your Fragment, you just need to give it the position of the fragment you want:
in your Adapter :
Must extends
FragmentPagerAdapter
into your ViewPager adapter class.If you use
FragmentStatePagerAdapter
then you will not able to find yourFragment
by itsID
How to use this method :-
You don't need to call
getItem()
or some other method at later stage to get the reference of aFragment
hosted insideViewPager
. If you want to update some data insideFragment
then use this approach: Update ViewPager dynamically?Key is to set new data inside
Adaper
and callnotifyDataSetChanged()
which in turn will callgetItemPosition()
, passing you a reference of yourFragment
and giving you a chance to update it. All other ways require you to keep reference to yourself or some other hack which is not a good solution.Create integer resource id in /values/integers.xml
Then in PagerAdapter getItem function:
Then in activity write this function to get fragment reference:
Get the fragment reference by calling the above function and then cast it to your custom fragment: