Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

FragmentStatePagerAdapter onPageSelected event

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

like image 633
Cheborra Avatar asked May 25 '14 16:05

Cheborra


1 Answers

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);
    }
}
like image 115
sergej shafarenka Avatar answered Sep 28 '22 00:09

sergej shafarenka