I have an app with a ViewPager
and three Fragment
s. I'm trying to figure out how to get the current Fragment
being viewed so I can get at its arguments.
I have an OnPageChangeListener
grabbing the current page index, but
ViewPager.getChildAt(int position);
returns a View
. What's the relationship between this View
and the current Fragment
?
Edit - Don't do this. If you're tempted to, read the comments for why it's a bad idea.
On the odd-chance you're still trying to solve this problem:
Extend
FragmentPagerAdapter
. In the constructor, build the Fragments you need and store them in a List (array/ArrayList) of Fragments.Then for
getItem(int position)
, you can do something likeI'm not sure if this is the generally accepted way of doing it but it worked for me.
Edit
This is really not a good way to go. If you plan on handling orientation changes or your app going into the background, then this will probably break your code. Please read the comments below this answer for more info. Rather use @James 's answer
PLEASE DON'T USE THIS
Make your adapter extend the following
FragmentStatePagerWithCurrentAdapter
class and instead of implementinggetItem
implement the same code intogetItemAtIndex
Set the
ViewPager
OnPageChangeListener
, to the instance of the adapter.When you need to access the current Fragment you just call
adapter.getCurrentItem()
.I used as reference the following blog post: http://tamsler.blogspot.com/2011/11/android-viewpager-and-fragments-part-ii.html
Definitive answer that works seamlessly (but small hack):
somewhere in page fragment's layout:
in fragment's onCreateView():
and method to return Fragment from ViewPager, if exists:
Yes, it's possible if you are using
FragmentStatePagerAdapter
.I finally found an answer that worked for me. Basically, you can access the fragment for a viewPager page by using the tag "android:switcher:"+R.id.viewpager+":0".
Jorge Garcia's FragmentStatePagerWithCurrentAdapter is a very good solution but it needs a minor improvement. In case the activity gets destroyed and re-created in response to a configuration change or something like that the getItem will not be called for the fragments that were saved and retrieved by the fragment manager. So I override getItem normally in my subclass and I put the following in the FragmentStatePagerWithCurrentAdapter
The instantiateItem is called every time the fragment in that position is accessed.