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
The best solution for you would be to override setUserVisibleHint()
. Make sure you extend FragmentPagerAdapter
. From its source code you can see it calls setUserVisibleHint(true)
for visible fragments too. I use it all the time and it works well.
// adapter
public static class PlayerAdapter extends FragmentStatePagerAdapter {
public PlayerAdapter(FragmentManager fm) {
super(fm);
}
@Override
public int getCount() {
return 6;
}
@Override
public Fragment getItem(int position) {
return new SimpleFragment();
}
}
// fragment
public class SimpleFragment extends Fragment {
private static final String TAG = BookControlsFragment.class.getSimpleName();
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_simple, container, false);
}
@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
Log.d(TAG, "setUserVisibleHint: " + isVisibleToUser);
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With