I have a FragmentStatePagerAdapter with 6 fragments inside.
Each Fragment connect's to the server and loads data.
Right now, the server connection is being done in Fragment.onStart(), that means that at any moment, I have 3 http requests going (the selected Fragment, and one to each side).
What I want is to have only one connection at the time, so I figure to use
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
@Override
public void onPageSelected(final int position)
{
CustomFragment fragment = (CustomFragment) myFragmentStatePagerAdapter.getItem(position);
fragment.onSelected();//do stuff in here
}
});
The thing is, getItem()
returns a new instance of the fragment, not yet added to the manager (and thus, not yet view created, etc).
Also, I've tried setUserVisibleHint(boolean isVisibleToUser)
but is not being call on visible, only on isVisibleToUser = false
So, how to achieve a "onPageSelected()" event for the Fragment?
Thanks in advance
Late to the train .Personally none of this approach is my favorite . They are hacky. Best way is using Adapters
setPrimaryItem(ViewGroup container, int position, Object object)
Inside
setPrimaryItem' save the current Fragment and use it inside
onPageSelected(final int position)`Code sample goes some thing like this ,
In your
FragmentStatePagerAdapter
use aHashMap
to hold the created Fragments, then you can access them later from your viewpager container (activity or fragment):Now, in your viewpager container(activity or fragment):
Since the onPageChangeListener is not called when the app is started, you will need to connect the first fragment. The important thing is that you will have a reference to the fragments returned by
getItem()
usingyourPagerAdapter.getFragment(currentPage)
.Edit:
I think this may be a better logic for
onPageSelected()
callback method:But you need to implement this methd on
FragmentStatePagerAdapter
:and get rid of
lastPage
data member.The best solution for you would be to override
setUserVisibleHint()
. Make sure you extendFragmentPagerAdapter
. From its source code you can see it callssetUserVisibleHint(true)
for visible fragments too. I use it all the time and it works well.What has worked for me is, in my pager adapter's
getItem
method, to save in a list my own reference to the custom fragment I return. The contract that both fragment pager adapter and fragment state pager adapter seem to follow means that the last fragment returned bygetItem(i)
will be the correct fragment to refresh in theonPageSelected(i)
method.I have only tested this technique with a fragment pager adapter and a reasonably small number of tabs. With a state pager adapter some testing would be needed to see if holding references to fragments causes memory use to increase.