3

I have a few Fragments in a ViewPager, and I've found the Fragment's onActivityCreated and onCreateView are both being called on the page before I expect.

For example, when the ViewPager transitions from page 2 to 3, then the Fragment at page 4's onCreateView and onActivityCreated are being called.

I'm intending to initiate a network request in onActivityCreated but it is starting one screen too soon. According to the Android docs, onActivityCreated is called "when the fragment's activity has been created and this fragment's view hierarchy instantiated." which leads me to believe I'm using the method correctly.

Zach Rattner
  • 20,745
  • 9
  • 59
  • 82
  • 1
    In a ViewPager, the neighboring views are loaded to be smoother loading. That's why they are called early – OneCricketeer Jul 18 '16 at 04:41
  • 1
    check this http://stackoverflow.com/questions/26400014/how-to-handle-network-calls-inside-a-fragment might help.try a demo @ https://github.com/shomeser/view-pager-fragment – Raghunandan Jul 18 '16 at 04:44

3 Answers3

5

For smooth loading of data view pager will load the fragments in advance. 1. If you are at 1st position(first fragment),so its automatically loads the next 2 fragments 2.Or if you are at 2 or later,then it will load previous one fragment and next fragment

Siva
  • 91
  • 6
3

ViewPager loads the next fragment for smooth transition between fragments, and that's why your next fragment's onCreate(), onCreateView() and onResume() is getting called. So, add onPageChangeListener on your viewPager like:

yourViewPager.addOnPageChangeListener(new OnPageChangeListener{
    @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
        @Override
        public void onPageSelected(int position) {
        switch(position){
            //your code for network operation
        }
    }
    @Override
        public void onPageScrollStateChanged(int state) {}

});     
Megha Maniar
  • 444
  • 5
  • 22
0

As others have mentioned, this is done for smooth loading of data in a view pager. What you can do though is call your code in onAattach() or when your fragment is visible to the user in onStart(). Android docs gives more details on lifecycle methods.

Sourabh86
  • 744
  • 10
  • 18