Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
548 views
in Technique[技术] by (71.8m points)

android - 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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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);
    }
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...